today I have a question about calculating summation with js.
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(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));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Qty1 : <input class="txt" type="number" name="qty" id="qty1"/><br>
Qty2 : <input class="txt" type="number" name="qty" id="qty2"/><br>
Qty3 : <input class="txt" type="number" name="qty" id="qty3"/><br>
Qty4 : <input class="txt" type="number" name="qty" id="qty4"/><br>
Qty5 : <input class="txt" type="number" name="qty" id="qty5"/><br>
Qty6 : <input class="txt" type="number" name="qty" id="qty6"/><br>
Qty7 : <input class="txt" type="number" name="qty" id="qty7"/><br>
Qty8 : <input class="txt" type="number" name="qty" id="qty8"/><br>
<br><br>
Total : <span id="sum">0</span><br>
This code only works when I input numbers directly in input fields. However, when I click on up-down arrows in input fields, the js code seems not working. How I can fix it? Thank you!
valueattribute? For instance, I set all my input fields attributevalue="5"then when I run the program the number 40 should be displayed as summation.