sum all values for table column based on class

前端 未结 2 682
礼貌的吻别
礼貌的吻别 2020-11-29 06:01

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

相关标签:
2条回答
  • 2020-11-29 06:36

    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);
    
    0 讨论(0)
  • 2020-11-29 06:37

    I have a JQuery plugin, Sumtr, that handles this pretty well if you want a summary row.

    Here is your example with the plugin.

    0 讨论(0)
提交回复
热议问题