Tùng Nguyễn
Tùng Nguyễn

Reputation: 103

Calculating summation of input fields have default value attribute by javascript

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/

Upvotes: 0

Views: 203

Answers (1)

symlink
symlink

Reputation: 12209

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>

Upvotes: 1

Related Questions