0

I got trouble in calculating summation with javascript

here my html code:

Qty1 : <input class="txt" type="number" value="2" name="qty" id="qty1"/><br>
Qty2 : <input class="txt" type="number" value="4" name="qty" id="qty2"/><br>
Qty3 : <input class="txt" type="number" value="3" name="qty" id="qty3"/><br>
Qty4 : <input class="txt" type="number" value="5" name="qty" id="qty4"/><br>

and my js code

$(document).ready(function(){

  //iterate through each textboxes and add keyup
  //handler to trigger sum event
  $(".txt").each(function() {

    $(this).on('input',function(){
      calculateSum();
    });
  });

});

function calculateSum() {

  var sum = 0;
  //iterate through each textboxes and add the values
  $(".txt").each(function() {

    //add only if the value is number
    if(!isNaN(this.value) && this.value.length!=0) {
      sum += parseFloat(this.value);
    }

  });
  //.toFixed() method will roundoff the final sum to 2 decimal places
  $("#sum").html(sum.toFixed(2));

}

this code still works fine if I input numbers directly in input fields. However, with the value attributes I expected that when I run this program it should be return result immediately. In my case, it should be returned 14 when I run the program, not 0. my jsfiddle link: https://jsfiddle.net/tfrqh974/1/

1
  • You are calling the calculateSum function on input only. If you call calculateSum before that as well then it would calculate with initial values Commented Dec 2, 2019 at 18:10

1 Answer 1

1

Simply call calculateSum() off the bat in document.ready:

$(document).ready(function() {

  $(".txt").each(function() {
    $(this).on('input', function() {
      calculateSum();
    });
  });
  calculateSum();
});


function calculateSum() {

  var sum = 0;

  $(".txt").each(function() {
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }

  });
  //.toFixed() method will roundoff the final sum to 2 decimal places
  $("#sum").html(sum.toFixed(2));

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Qty1 : <input class="txt" type="number" value="2" name="qty" id="qty1" /><br> Qty2 : <input class="txt" type="number" value="4" name="qty" id="qty2" /><br> Qty3 : <input class="txt" type="number" value="3" name="qty" id="qty3" /><br> Qty4 : <input class="txt"
  type="number" value="5" name="qty" id="qty4" /><br>
<div id="sum"></div>

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

Comments

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.