jQuery calculate sum of values in all text fields

前端 未结 9 1232
渐次进展
渐次进展 2020-11-29 19:52

I have an order form with about 30 text fields that contain numerical values. I\'d like to calculate the sum of all those values on blur.

I know how to select all te

相关标签:
9条回答
  • 2020-11-29 20:16

    A tad more generic copy/paste function for your project.

    sumjq = function(selector) {
        var sum = 0;
        $(selector).each(function() {
            sum += Number($(this).text());
        });
        return sum;
    }
    
    console.log(sumjq('.price'));
    
    0 讨论(0)
  • Use this function:

    $(".price").each(function(){
    total_price += parseInt($(this).val());
    });
    
    0 讨论(0)
  • 2020-11-29 20:24
    $('.price').blur(function () {
        var sum = 0;
        $('.price').each(function() {
    
            if($(this).val()!="")
             {
                sum += parseFloat($(this).val());
             }
    
        });
            alert(sum);
    });​​​​​​​​​
    

    JS Fiddle

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