【问题标题】:SUM dynamically added fields in jQuerySUM 在 jQuery 中动态添加字段
【发布时间】:2018-01-03 03:56:35
【问题描述】:

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

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 的名称部分做错了,或者我只是没有一起做。我应该说我的“存放”小计的文本字段如下:

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

【问题讨论】:

标签: javascript jquery html arrays


【解决方案1】:

如果我理解你,你想得到输入中所有值的总和?! 试试看:

$(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)
});

我建议使用类选择器而不是复杂选择器。代码会很简单。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2016-02-16
    • 2013-10-22
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多