Jquery,计算字段总和(动态)

我有一个搜索,但没有发现任何我真正想做的事情。

我有一个动态表单,每个项目有2个输入框,1是一个值,另一个是数量。 例如

所以我需要计算val_1 X val_1_1 = total然后在结尾添加总数(对于每个项目)。

我希望我能找到适合无限项目的东西。

怎么样: jsFiddle示例

jQuery的:

 function doCalc() { var total = 0; $('tr').each(function() { $(this).find('span.amount').html($('input:eq(0)', this).val() * $('input:eq(1)', this).val()); }); $('.amount').each(function() { total += parseInt($(this).text(),10); }); $('div.total_amount').html(total); } $('button').click(doCalc);​ 

您最大的问题是,您没有简单的方法来确保您确定哪些字段是值,哪些是数量。 您编写它的方式,任何带有单个下划线的字段名称都可以是值,但是名为“some_value_1”的字段呢?

只要没有人向表中添加更多列,使用表定位就是一个很好的解决方案。 我认为您应该使用一个类来指示哪些字段是值,哪些是数量。

无论如何,我的解决方案,为清晰起见略显冗长:

  




我想这会做你想要的。

 function calcCost() { var total = 0; $('table tr').each( function() { if ( $(this).find('td').length && $(this).find('td input').length ) { var quant = parseInt($(this).find('td input').eq(0).val()), price = parseInt($(this).find('td input').eq(1).val()); $(this).find('.amount').html(quant * price); total += quant * price; } }); $('.total_amount').html(total); } calcCost(); $('input').on('keyup', function() { calcCost(); }); 

Item Value Quantity Total
Item $
Item $
Total event cost (viability) $
total