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 nu
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);
I have a JQuery plugin, Sumtr, that handles this pretty well if you want a summary row.
Here is your example with the plugin.