sum all values for table column based on class

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);

Leave a Comment