How to sum various values stored in one textfield?

Viewed 60

I am trying to build a very simple web application.

I want the values of one textfield to be stored after I press a button, and to be added.

For example, if I typed 3, clicked submit, then 5, clicked submit, and then 2, I would like the result to be 10, but I'm not sure how to do this.

<style media="screen">
    .error {
      display: none;
    }
    .number {
      display: none;
    }
  </style>

<body>
  <form>
    <label for="numberInput">Write a number: </label>
    <input type="text" name="numberInput" class="numberInput" id="numberInput">
    <button type="button" name="submitBtn" class="submitBtn" id="submitBtn">Submit</button>
    <div id="error" class="error">
    </div>
    <div id="number" class="number">
    </div>
    <script type="text/javascript">
      $("#submitBtn").on("click", function() {
        if ($("#numberInput").val() != "") {
          $("#error").hide();
          $("#error").text("");
          var storedValue = $("#numberInput").val();
          $("#number").show();
          $("#number").text(storedValue);
        } else {
          $("#error").show();
          $("#error").text("Please complete the above field.");
        }
      });
    </script>

If I were to type 5 and then 2, I expect the result to be 7, however, the actual result that appears is 2.

5 Answers

I just changed your code slightly (all changes are marked with comments).

Things to note:

  1. If you make storedValue a global variable and initialize it to 0 then you can keep adding the #numberInput value to it every time the form is submitted (and the value from the previous submission will be kept). Note: storedValue will be reset to 0 everytime you reload the page.
  2. You need to cast the numberInput value to an int otherwise it will be interpreted as a string and the numeric calculations you are making will not work as expected.

Also I don't see a closing tag for the form in your code so I have added that.

<!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    <style media="screen">
       .error {
          display: none;
        }
        .number {
          display: none;
      }
    </style>
    <script src="jquery.min.js"></script>

    </head>
      <body>
        <form>
          <label for="numberInput">Write a number: </label>
          <input type="text" name="numberInput" class="numberInput" id="numberInput">
          <button type="button" name="submitBtn" class="submitBtn" id="submitBtn">Submit</button>

        </form>
        <div id="error" class="error">
        </div>
        <div id="number" class="number">
        </div>

        <script type="text/javascript">
          //create a global variable so we can keep values stored from previous form submissions.
          //initialize it to 0. Therefore everytime the page reloads the value will
          //reset to 0.
          var storedValue = 0;

          $("#submitBtn").on("click", function() {
            if ($("#numberInput").val() != "") {
              $("#error").hide();
              $("#error").text("");
              //we need to cast the input value to an int otherwise it will be 
              //interpreted as a string.
              //add the input value to the current storedValue.
              storedValue = storedValue + parseInt($("#numberInput").val());
              $("#number").show();
              $("#number").text(storedValue);
            } else {
              $("#error").show();
              $("#error").text("Please complete the above field.");
            }
          });
        </script>
      </body>
    </html>

JavaScript:

  1. Add a default 0 value inside your #number div so you an add an input number to it later.
  2. Assign the input, the button, the #number div and the #error div to variable input, btn, result and error respectively.
  3. Add a click event listener to your btn variable that runs a function say, calculate().
  4. Inside the function, add an if statement that checks if the input has any value and if the input value is a number.
  5. If both conditions are not met, append an error like "Please enter a valid number" inside your #error div but if both conditions are met, parse the input value to an integer and add it to the current parsed number inside your #number div and replace the number inside your #number div with the new added number.

Check and run the following Code Snippet for a practical example of the above:

/* JavaScript */

var input = document.getElementById("numberInput");
var btn = document.getElementById("submitBtn");
var result = document.getElementById("number");
var error = document.getElementById("error");

function calculate() {
    if (input.value && !isNaN(input.value)) {
      error.innerHTML = "";
      result.innerHTML = parseInt(result.innerHTML) + parseInt(input.value);
    } else {
        error.innerHTML = "Please enter a valid number";
    }
}

btn.addEventListener("click", calculate);
<!-- HTML -->

<form>
  <label for="numberInput">Write a number: </label>
  <input type="text" name="numberInput" class="numberInput" id="numberInput">
  <button type="button" name="submitBtn" class="submitBtn" id="submitBtn">Submit</button>
  <div id="number" class="number">0</div>
  <div id="error" class="error"></div>
</form>


jQuery:

I personally prefer pure JavaScript over jQuery but if you want a jQuery version of the above, you can check and run the Code Snippet below:

function calculate() {
    if ($("#numberInput").val() && !isNaN($("#numberInput").val())) {
      $("#error").html("");
      $("#number").html(parseInt($("#number").text()) + parseInt($("#numberInput").val()));
    } else {
        $("#error").html("Please enter a valid number");
    }
}

$("#submitBtn").click(calculate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <label for="numberInput">Write a number: </label>
  <input type="text" name="numberInput" class="numberInput" id="numberInput">
  <button type="button" name="submitBtn" class="submitBtn" id="submitBtn">Submit</button>
  <div id="number" class="number">0</div>
  <div id="error" class="error"></div>
</form>

With some changes to your code, it can be done as below:

<html>
<head>
<style media="screen">
    .error {
      display: none;
    }
    .number {
      display: none;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
  <form>
    <label for="numberInput">Write a number: </label>
    <input type="hidden" id="hiddenTotal" value="0" />
    <input type="text" name="numberInput" class="numberInput" id="numberInput">
    <button type="button" name="submitBtn" class="submitBtn" id="submitBtn">Submit</button>
    <div id="error" class="error">
    </div>
    <div id="number" class="number">
    </div>
    <script type="text/javascript">
        var total = 0;
      $("#submitBtn").on("click", function() {
        if ($("#numberInput").val() != "") {
          $("#error").hide();
          $("#error").text("");
          total = parseInt($("#hiddenTotal").val());          
          var inputValue = $("#numberInput").val();
          total = total + parseInt(inputValue);
          $("#hiddenTotal").val(total);

          if(total > 0)
          {
            $("#number").show();
            $("#number").text(total);
          }
        } else {
          $("#error").show();
          $("#error").text("Please complete the above field.");
        }
      });
    </script>
</html> 

I would add to an array

numbers.push($("#numberInput").val());

then once they hit the submit button loop over the array and add the values

numbers.forEach(function(element) {
  total += element;
});

you will have to declare total outside of the loop, and you might have to convert the elements in the array to a number using parseInt(element)

You need to store the last added result.

let globalValue = 0;

function handleInput(){
   let newInput = document.getElementById('input').value;
   globalValue += Number( newInput ) || 0;
   console.log( globalValue )
}
<input type='input' id='input' value=''>
<input type='button' onclick='handleInput()'>

Related