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/