Lena Kir
Lena Kir

Reputation: 101

Total sum of all numbers the user has input in HTML Javascript

I need help to create a function that:

  1. Contains information of the total sum of all numbers the user has input so far is calculated, printed to console, and stored on HTML page.
  2. When the total sum is larger than 100, the function prints "it's over" to console.

Any suggestions? Below is what I've got so far:

function adder() {
  var num1 = parseInt(document.getElementById("myform").elements["num1"].value);
  var num2 = parseInt(document.getElementById("myform").elements["num2"].value);
  var total = num1 + num2;
  document.getElementById("p1").innerHTML = total;
}
<form id="myform">
  First Number: <input type="text" name="num1"><br /><br /> Second Number: <input type="text" name="num2"><br /><br />
</form>
<button onclick="adder()"> Submit</button><br><br>
<p id="p1">Results Are Here</p>

Upvotes: 1

Views: 6396

Answers (2)

diegorodny
diegorodny

Reputation: 412

Quick mod to above answer to stop the counting after reaches > 100.

var total = 0;

function adder() {
  var num1 = parseInt(document.getElementById("myform").elements["num1"].value);
  var num2 = parseInt(document.getElementById("myform").elements["num2"].value);
  if (total > 100){
    console.log("It's over!");
  } else {
    total += num1 + num2;
    document.getElementById("p1").innerHTML = total;
  }
}
<form id="myform">
  First Number: <input type="text" name="num1"><br /><br /> Second Number: <input type="text" name="num2"><br /><br />
</form>
<button onclick="adder()"> Submit</button><br><br>
<p id="p1">Results Are Here</p>

Upvotes: 1

Angelos Chalaris
Angelos Chalaris

Reputation: 6747

You should define and initialize total to 0 outside adder() so that you can add the fields values to the existing sum. Here's an example:

var total = 0;

function adder() {
  var num1 = parseInt(document.getElementById("myform").elements["num1"].value);
  var num2 = parseInt(document.getElementById("myform").elements["num2"].value);
  total += num1 + num2;
  document.getElementById("p1").innerHTML = total;
  if (total > 100) console.log("It's over!");
}
<form id="myform">
  First Number: <input type="text" name="num1"><br /><br /> Second Number: <input type="text" name="num2"><br /><br />
</form>
<button onclick="adder()"> Submit</button><br><br>
<p id="p1">Results Are Here</p>

On a side note if your <button> is part of your <form>, it will cause the page to refresh, so adding type="button" solves this issue in that case and you can see the result properly.

Upvotes: 2

Related Questions