我的问题是计算工作正常,但是当删除行时,计算不会根据创建新行后的计算进行更新,并且在执行计算后只有值在更新..请帮助我纠正这个问题。
$(document).on('change', 'tr td:nth-child(6), tr td:nth-child(5), tr td:nth-child(4)', .
'remove3'
function() {
var total = 0;
var sqty = 0;
var tr = $(this).parent();
var qty = tr.find('td:nth-child(4)').find('input').val();
var rate = tr.find('td:nth-child(5)').find('input').val();
var amount = qty * rate;
tr.find('td:nth-child(6)').find('input').val(amount);
var tbody = tr.parent();
$(tbody).find('tr').each(function() {
total += Number($(this).find('td:nth-child(6)').find('input').val());
sqty += Number($(this).find('td:nth-child(4)').find('input').val());
});
$('#TieTotal').val(total);
$('#SQty').val(sqty);
$('#Grandtot').val(total);
})
自动创建下一行的脚本:
$('.tb3').on('keydown', 'input', function(e) {
var keyCode = e.keyCode;
if (keyCode !== 9) return;
var $this = $(this),
$lastTr = $('tr:last', $('.tb3')),
$lastTd = $('td:last', $lastTr);
if (($(e.target).closest('td')).is($lastTd)) {
var cloned = $lastTr.clone();
cloned.find('input').val('');
$lastTr.after(cloned);
}
});
删除行的脚本:
$(document).on('click', '.remove3', function() {
var trIndex = $(this).closest("tr").index();
if (trIndex > 0) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
}
});
最佳答案
假设您有一个类似的 HTML(可以是动态绘制的 HTML)。
<tr>
<td><input class="Qty" type="text" value="2"/></td>
<td><input class="Rate" type="text" value="200"/></td>
<td><input class="Value" type="text"/></td>
<td><button type="button" class="remove3">X</button></td>
</tr>
此外,假设您已将更新总数的方法更改为如下所示(已准备好内部文档)。这是示例代码,您的实际代码可能会有所不同。您需要做的就是将触发 on("keyup change")
(或您喜欢的方式)保留在 document.ready()
中。
$('.Qty').on("keyup change",function(){
var $row = $(this).closest("tr");
var price = 0;
var total = 0;
$('.tb3 tr').each(function() {
var qty = $(this).find('.Qty').val();
var rate = $(this).find('.Rate').val();
var price = qty * rate;
$(this).find('.Value').val(price);
total += parseFloat(price);
});
$('#TieTotal').val(total.toFixed(2));
});
现在,当您每次按下具有类 .remove3
的按钮时,您在删除行方面都是正确的。在同一 block 中,您可以通过触发具有类 .Qty
的元素的 change()
事件来轻松更新总数。 (这就是总数首先更新的方式)见下文,
$('.remove3').click(function () {
var trIndex = $(this).closest("tr").index();
if (trIndex > 0) {
$(this).closest("tr").remove();
$('.Qty').trigger('change');
} else {
alert("Sorry!! Can't remove first row!");
}
});
fiddle , https://jsfiddle.net/anjanasilva/dykm6wau/
希望对您有所帮助。 干杯!
关于javascript - 从表中删除行时如何更改计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53096329/