SUM在jQuery中动态添加的字段 [英] SUM dynamically added fields in jQuery

查看:69
本文介绍了SUM在jQuery中动态添加的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,可以在其中动态向表中添加行.但我希望能够在表格底部添加小计.到目前为止,我有类似的东西:

I have a table where I can dynamically add rows to a table. But I'd like to be able to include a subtotal at the bottom of the table. So far I have something like:

JavaScript:

JavaScript:

$(document).on('change', 'input[name^="shipment_details[charge][]"]', function() {
    var sum = 0;
    $('input[name^="shipment_details[charge][]"]').each(function(){
        sum += +$(this).val();
    });
    $('input[name^="freightBillSubtotal"]').val(sum);
});

HTML

<input type="text" class="qty1" value="" name="shipment_details[charge][]"/>
<input type="text" class="qty1" value="" name="shipment_details[charge][]"/>
<input type="text" class="qty1" value="" name="shipment_details[charge][]"/>
<input type="text" class="qty1" value="" name="shipment_details[charge][]"/>
<input type="text" class="qty1" value="" name="shipment_details[charge][]"/>

但是当我在JSFiddle中玩游戏时这是行不通的,所以我很好奇我是否将javascript的名称部分做错了,或者我只是没有一起做.我应该说,我的用于在何处存放"小计的文本字段如下:

But this doesn't work when I play with in JSFiddle, so I am curious if I am doing the name portion of the javascript wrong, or if I am just not doing it all together. I should say that my text field for where to "deposit" the subtotal is the following:

<input type="text" readonly name="freightBillSubtotal" id="freightBillSubtotal">

推荐答案

如果我理解您的意思,您想获取输入中所有值的总和吗?! 试试吧:

If I understand you , you want to get sum of all values in inputs?! try it:

$(document).on('change', 'input[name^="shipment_details[charge][]"]', function() { 
    var sum = 0;
    $('input[name^="shipment_details[charge][]"]').each(function(index,elem){
      let value = $(elem).val();
      if(typeof value ==="number"){
         sum += +value;
      }
    });
$('input[name^="freightBillSubtotal"]').val(sum);
  console.log(sum)
});

我建议使用类选择器而不是复杂的选择器.代码将很简单.

I recommend to use class selectors instead complex selector. Code will be simple.

这篇关于SUM在jQuery中动态添加的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆