如何使用嵌套表单动态查找逐行总计和总计?
如何使用嵌套表单动态查找逐行总计和总计?
我使用了嵌套表单。这是我的jQuery代码,用于计算发票应用程序的逐行总计和总计。
$("tr.sum_hours td").on("change", '.hr', function() { row = $(this).parent("td").parent(); total = 0; qnt = 0; rate = 0; discount = 0; tax = 0; $(row).find("td input.hr").each(function(index) { if ($(this).val() !== "") { if ($(this).hasClass('quantity')){ qnt = parseFloat($(this).val()); } if($(this).hasClass('rate')){ rate = parseFloat($(this).val()); } if($(this).hasClass('discount')){ discount = parseFloat($(this).val()); } if($(this).hasClass('tax')){ tax = parseFloat($(this).val()); } return total = ((qnt*rate)-(discount)+(tax)) } }); $(row).find("td input.total").val(total); grand_total = 0; return $(".total").each(function() { if ($("#invoice_grand_total") !== "") { grand_total = grand_total + parseFloat($(this).val()); } return $("#invoice_grand_total").val(grand_total); }); });
这是我的HTML代码。
货品名称 | 描述 | 数量 | 单价 | 折扣 | 税费 | 总计 | 操作 |
---|---|---|---|---|---|---|---|
删除 | |||||||
删除 |
该代码适用于静态行,但对于动态添加的行无效。请帮忙。
问题的出现原因是在jQuery的代码中,使用了错误的选择器。解决方法是将错误的选择器替换为正确的选择器。
具体来说,代码中使用了以下代码:
$("tr.sum_hours td").on("change", '.hr', function() {
而应该替换为以下代码:
$("body").on("change", 'tr.sum_hours td .hr', function() {
如果需要更多的解释,请参考以下链接:jQuery click function doesn't work after ajax call?
以下是一个示例链接,展示了修改后的代码的jsfiddle演示:http://jsfiddle.net/suhailvs/t67pn/1/