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>

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

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 @Manu Sampablo
@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)
@Testing999 I'm testing it and everything seems fine, make sure you didn't input a letter unintentionally
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>

5 Comments

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 Sorry for the late reply, I have made the necessary edit to the above answer, hope it helps. Now the code is more organised.
Can I ask why you used .textContent
@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.
@Testing999 These are some good articles: First Second

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.