2

I have written the below code to get the form data to be displayed on the page. What other methods can I use to re-write the below code to include form validation. I'm a beginner to javascript and just needed some guidance or a code snippet to help.

JSFiddle link: https://jsfiddle.net/jphfzgdq/

<head>
  <script type="text/javascript">
    function collect(frm) { 
    document.getElementById("results").innerHTML+="Name: "+frm.nm.value+"<br>Age: "+frm.ag.value+"<hr>"
    frm.reset();
    } 
    </script>
  <style>
  /* #entries,#results{float:left} */
  </style> 
  </head>
  <body>
  <div id="entries">
  <form name ="myform">
  Enter name: <input type="text" name="nm"/><br>
  Enter age: <input type="text" name="ag"/><br>
  <input type="button" value="display" onclick="collect(this.form)"/>
  </form>
  </div>
  <div id="results"></div>

</body>
Ali Esmailpor
  • 1,209
  • 3
  • 11
  • 22
Testing999
  • 23
  • 4

2 Answers2

1

I think this is what you are asking for

<head>
    <script type="text/javascript">
        var totalAge = 0;
        
        function collect(frm) { 
        var name = frm.nm.value;
        var age = parseInt(frm.ag.value);
        
        totalAge += age;
        
        try {
            if (name == "" || name == null) {
            alert('Enter your name');
          } 
          else if (age == "" || age == null || age == NaN) {
            alert('Enter a valid age');
          }
          else {
            document.getElementById("results").innerHTML+="Name: "+ name +"<br>Age: "+ age + "<br>total age: "+ totalAge +"<hr>"
                frm.reset();
          }
        }
        catch (e) {
         console.log(e);
        }
        
        } 
        </script>
    <style>
    /* #entries,#results{float:left} */
    </style> 
    </head>
    <body>
    <div id="entries">
    <form name ="myform">
    Enter name: <input type="text" name="nm"/><br>
    Enter age: <input type="number" name="ag"/><br>
    <input type="button" value="display" onclick="collect(this.form)"/>
    </form>
    </div>
    <div id="results"></div>
  
    </body>
Manu Sampablo
  • 350
  • 5
  • 17
  • I appreciate your help. – Testing999 Mar 20 '21 at 20:08
  • One more query was if you wanted to get a total figure of the age number entered each time you submit the form. i.e. a running total figure on the corner similar to a shopping cart total @Manu Sampablo – Testing999 Mar 20 '21 at 20:21
  • 1
    @Testing999 I've made the necesary changes. Those are: 1- add a total age variable 2- add the age to the `totalAge` var everytime it is submitted the form 3- Set age `type="number"` instead of `type="text"` (in the form) – Manu Sampablo Mar 20 '21 at 20:41
  • 1
    @Testing999 I'm testing it and everything seems fine, make sure you didn't input a letter unintentionally – Manu Sampablo Mar 20 '21 at 21:41
1

I just made a simple age validation.

function collect(frm) {
  if (Number(frm.ag.value) >= 18) {
    document.getElementById("results").innerHTML +=
      "Name: " + frm.nm.value + "<br>Age: " + frm.ag.value + "<hr>";
    document.getElementById("warn").textContent = "";
    frm.reset();
  } else {
    document.getElementById("warn").textContent =
      "18+ Are only allowed!";
  }
}
#warn {
  color: red;
}
<div id="entries">
  <form name="myform">
    Enter name: <input type="text" name="nm" /><br> Enter age: <input type="number" name="ag" /><br>
    <input type="button" value="display" onclick="collect(this.form)" />
  </form>
</div>
<h4 id="warn"></h4>
<div id="results"></div>

EDIT:

You were not doing it in a proper way so tried to make it better.

const nameInput = document.getElementById("nameInput");
const ageInput = document.getElementById("ageInput");
const btnInput = document.getElementById("btnInput");

const results = document.getElementById("results");
const warn = document.getElementById("warn");
const ageCounter = document.getElementById("totalAgeCounter");

let ageCount = 0;

function collectData() {
  if (nameInput.value !== "" && Number(ageInput.value) >= 18) {
    results.innerHTML += `Name: ${nameInput.value} <br>Age: ${ageInput.value} <hr>`;

    ageCount += Number(ageInput.value);
    ageCounter.textContent = ageCount;

    warn.textContent = "";
    nameInput.value = "";
    ageInput.value = "";
  } else {
    warn.textContent = "18+ Are only allowed!";
  }
}

btnInput.addEventListener("click", collectData);
#warn {
  color: red;
}

#totalAgeCounter {
  width: 50px;
  height: 50px;
  display: grid;
  place-items: center;
  background-color: blue;
  position: absolute;
  top: 20px;
  right: 20px;
  color: #fff;
  border-radius: 50%;
  font-weight: bolder;
  font-size: 18px;
}
<div id="entries">
  <form name="myform">
    Enter name:
    <input type="text" id="nameInput" />
    <br /> Enter age:
    <input type="number" id="ageInput" />
    <br />
    <input type="button" value="display" id="btnInput" />
  </form>
</div>

<h4 id="warn"></h4>
<div id="results"></div>
<div id="totalAgeCounter"></div>
Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
  • I appreciate your help. One more query was if you wanted to get a total figure of the age number entered each time you submit the form. i.e. a running total figure on the corner similar to a shopping cart total – Testing999 Mar 20 '21 at 20:14
  • 1
    @Testing999 Sorry for the late reply, I have made the necessary edit to the above answer, hope it helps. Now the code is more organised. – Manas Khandelwal Mar 20 '21 at 20:51
  • Can I ask why you used .textContent – Testing999 Mar 20 '21 at 21:10
  • @Testing999 If we want to add some `HTML` then we use `innerHTML` but if we just want to add some text we can use `textContent`. We can use `innerHTML` here at the place of `textContent`. Also `textContent` returns the text inside the element but `innerHTML` retuns text with `HTML` tags. – Manas Khandelwal Mar 21 '21 at 04:36
  • 1
    @Testing999 These are some good articles: [First](https://betterprogramming.pub/whats-best-innertext-vs-innerhtml-vs-textcontent-903ebc43a3fc) [Second](https://stackoverflow.com/a/21311670/11171286) – Manas Khandelwal Mar 21 '21 at 04:38