首页 > 解决方案 > 从表中删除行时如何更改计算

问题描述

我的问题是计算工作正常,但是当该行被删除时,计算并没有根据创建新行后的计算进行更新,并且在执行计算之后只有值正在更新..请帮助我纠正这个问题。

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

标签: javascriptphpcodeigniter

解决方案


假设您有一个类似 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您在删除行方面是正确的。在同一块中,您可以通过触发change()具有类的元素事件来轻松更新总数.Qty。(这就是总数首先更新的方式)见下文,

$('.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!");
    }      
});

小提琴, https: //jsfiddle.net/anjanasilva/dykm6wau/

我希望这有帮助。干杯!


推荐阅读