I have the following jQuery code for finding the sum of all table rows, now it finds the sum on keyup. I want the sum to be already calculated. I wanted to have a hidden field like an input with a value, so the sum is automatically calculated.
Now there is an input, the user writes some number and than he gets the sum, I am trying to get the sum automatically. The number is already going to be in the table the user will not write anything.
HTML:
<table width="300px" border="1" style="border-collapse: collapse; background-color: #E8DCFF">
<tr>
<td width="40px">1</td>
<td>Number</td>
<td><input class="txt" type="text" name="txt" /></td>
</tr>
<tr>
<td>2</td>
<td>Number</td>
<td><input class="txt" type="text" name="txt" /></td>
</tr>
<tr>
<td>3</td>
<td>Number</td>
<td><input class="txt" type="text" name="txt" /></td>
</tr>
<tr id="summation">
<td colspan ="2" align="right">
Sum :
</td>
<td align="center"><span id="sum">0</span></td>
</tr>
</table>
jQuery:
$(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);
$(this).css("background-color", "#FEFFB0");
}
else if (this.value.length != 0){
$(this).css("background-color", "red");
}
});
$("#sum").html(sum.toFixed(2));
}
If I understood correctly you did want to sum change while user writes the input value. This can be achieved by changing your ready function to this:
Demo