自动计算总和以动态添加和删除行-jQuery

时间:2019-10-31 11:51:10

标签: javascript jquery html

如何为动态添加和删除行计算总和,我可以创建一些代码,但是它只能工作于添加行,当我单击som不会进行计算时,我只需要在添加行和删除行时自动计算总和。

  

当我删除行时,总和不减少。

这里是小提琴。.

FIDDLE HERE

这是我的摘录。

$(document).ready(function() {
  var counter = 0;

  $("#add_Row").on("click", function() {
    var newRow = $("<tr>");
    var cols = "";

   
    cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
    newRow.append(cols);

    var defVal = $("select[name=acctname]").find(":selected").val();
    if (defVal) {
      $("select[name=accountName]").find(`option[value=${defVal}]`).hide();
    }
    $("table.order-list").append(newRow);
    setValCashVal('accountName'.concat(counter));
    bindScript();
    counter++;
  });

  // delete function
  $("table.order-list").on("click", ".ibtnDel", function(_event) {
    $(this).closest("tr").remove();
    counter -= 1
  });

});

/* total */

$('body').on('change', '[data-action="sumDebit"]', function() {
    var total = 0;
    $('[data-action="sumDebit"]').each(function(_i, e) {
        var val = parseFloat(e.value);
        if (!isNaN(val)) 
            total += val;
    });
    $('#totaldbt').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row clearfix">
    <div class="col-md-12 column">

      <table class="table table-bordered table-hover order-list" id="tab_logic">
        <thead>
          <th class="text-center">
            Debit*
          </th>
        </thead>
        <tbody>
          <input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
        </tbody>
      </table>

    </div>
  </div>
</div>

<!-- total -->


<div class="row">
  <div class="col-6">
    <div class="cashTotal">
      <p class="tableTotal">Total:</p>
    </div>
  </div>
  <div class="col-6">
    <input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
  </div>
</div>

4 个答案:

答案 0 :(得分:2)

删除行时,不会触发

r :: Double -> Double r x = round (x) 事件。我建议使用一个单独的函数来评估总数,并在更改以及行删除时调用它。

请参阅小提琴:https://jsfiddle.net/46fnv9ux/

change

答案 1 :(得分:1)

删除添加时完成的行时,只需执行相同的操作即可。

$(document).ready(function() {
  var counter = 0;

  $("#add_Row").on("click", function() {
    var newRow = $("<tr>");
    var cols = "";

   
    cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
    newRow.append(cols);

    var defVal = $("select[name=acctname]").find(":selected").val();
    if (defVal) {
      $("select[name=accountName]").find(`option[value=${defVal}]`).hide();
    }
    $("table.order-list").append(newRow);
    setValCashVal('accountName'.concat(counter));
    bindScript();
    counter++;
  });

  // delete function
  $("table.order-list").on("click", ".ibtnDel", function(_event) {
    $(this).closest("tr").remove();
    counter -= 1
     var total = 0;
    $('[data-action="sumDebit"]').each(function(_i, e) {
        var val = parseFloat(e.value);
        if (!isNaN(val)) 
            total += val;
    });
    $('#totaldbt').val(total);
  });

});

/* total */

$('body').on('change', '[data-action="sumDebit"]', function() {
    var total = 0;
    $('[data-action="sumDebit"]').each(function(_i, e) {
        var val = parseFloat(e.value);
        if (!isNaN(val)) 
            total += val;
    });
    $('#totaldbt').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row clearfix">
    <div class="col-md-12 column">

      <table class="table table-bordered table-hover order-list" id="tab_logic">
        <thead>
          <th class="text-center">
            Debit*
          </th>
        </thead>
        <tbody>
          <input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
        </tbody>
      </table>

    </div>
  </div>
</div>

<!-- total -->


<div class="row">
  <div class="col-6">
    <div class="cashTotal">
      <p class="tableTotal">Total:</p>
    </div>
  </div>
  <div class="col-6">
    <input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
  </div>
</div>

答案 2 :(得分:1)

删除按钮单击事件未重新计算总数。

@Devis&Bilal的答案将添加所有值以找到总和。相反,您可以从总数中减去已删除行的值。

如下修改删除功能,以从总计中减去删除的值。

  // delete function
  $("table.order-list").on("click", ".ibtnDel", function(_event) {
    counter -= 1
    var total = $('#totaldbt').val();
    var delVal = $(this).closest("tr").find('input').val();
    var val = parseFloat(delVal);
    if (!isNaN(val))
      total -= val;
    $('#totaldbt').val(total);
    $(this).closest("tr").remove();
  })

;

答案 3 :(得分:1)

我将计算移到一个函数calculateTotal,并为删除按钮添加了一个事件,以便在删除任何行时重新计算总数:

$(document).ready(function() {
  var counter = 0;

  $("#add_Row").on("click", function() {
    var newRow = $("<tr>");
    var cols = "";


    cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
    cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
    newRow.append(cols);

    var defVal = $("select[name=acctname]").find(":selected").val();
    if (defVal) {
      $("select[name=accountName]").find(`option[value=${defVal}]`).hide();
    }
    $("table.order-list").append(newRow);
    setValCashVal('accountName'.concat(counter));
    bindScript();
    counter++;
  });

  // delete function
  $("table.order-list").on("click", ".ibtnDel", function(_event) {
    $(this).closest("tr").remove();
    counter -= 1
  });

});

/* total */

$('body').on('change', '[data-action="sumDebit"]', function(){
calculateTotal();
});

$(document).on( 'click', '.ibtnDel', function () {
	calculateTotal();
});

function calculateTotal(){
  var total = 0;
  $('[data-action="sumDebit"]').each(function(_i, e) {
    var val = parseFloat(e.value);
    if (!isNaN(val))
      total += val;
  });
  $('#totaldbt').val(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row clearfix">
    <div class="col-md-12 column">

      <table class="table table-bordered table-hover order-list" id="tab_logic">
        <thead>
          <th class="text-center">
            Debit*
          </th>
        </thead>
        <tbody>
          <input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
        </tbody>
      </table>

    </div>
  </div>
</div>

<!-- total -->


<div class="row">
  <div class="col-6">
    <div class="cashTotal">
      <p class="tableTotal">Total:</p>
    </div>
  </div>
  <div class="col-6">
    <input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
  </div>
</div>

或者您可以通过以下方式进行操作:

$('body').on('change', '[data-action="sumDebit"]', function(){
    calculateTotal();

  $('#tab_logic').on( 'click', '.ibtnDel', function () {
    calculateTotal();
  });  
});

function calculateTotal(){
  var total = 0;
  console.log(total);
  $('[data-action="sumDebit"]').each(function(_i, e) {
    var val = parseFloat(e.value);
    if (!isNaN(val))
      total += val;
  });
  $('#totaldbt').val(total);
}