sum all values for table column based on class
I'm trying to retrieve the sum of all values in a td based on a specific class. The code does not throw up any errors but my sum keeps resulting in "0".
Do the numerical values have to be specified in a particular way? I saw some other answers here on SO from where have imitated the code, and i dont see any real difference between mine and theirs so im confused as to why mine isnt working.
Here is a tutorial i followed for reference: http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html
Here is my javascript
$(document).ready(function(){
$('.price').each(function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each td based on class and add the values
$(".price").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$('#result').text(sum);
};
Here is my html
<table border="1">
<tr>
<th>Item</th>
<th>Price</th>
</tr>
<tr>
<td>Banana</td>
<td class ="price">50</td>
</tr>
<tr>
<td>Apple</td>
<td class ="price">100</td>
</tr>
</table>
<div id="result"></div>
Solution 1:
You want to use text()
instead of this.value
(since <td>
s don't have a "value"):
var sum = 0;
// iterate through each td based on class and add the values
$(".price").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
Also, you're looping over your .price
elements (calling calculateSum
) multiple times. You can replace
$(document).ready(function(){
$('.price').each(function() {
calculateSum();
});
});
with
$(calculateSum);
Solution 2:
I have a JQuery plugin, Sumtr, that handles this pretty well if you want a summary row.
Here is your example with the plugin.