【问题标题】:How to do calculation in dynamically added row如何在动态添加的行中进行计算
【发布时间】:2021-02-24 11:35:25
【问题描述】:

我想要做的是当用户输入数量和单价时,总金额会自动提示,但现在的问题是当用户添加新行时,动态行不进行计算。有人知道怎么做吗?

我不确定我的编码是对还是错,因为我对 jQuery 不是很熟悉。 Fiddle

<table>
  <thead>
    <tr>
      <th>Action</th>
      <th>Description</th>
      <th>Qty</th>
      <th>Unit Price</th>
      <th>Amount</th>
       <th>Tax</th>
    </tr>
  </thead>
  <tbody class="items_table">
    <tr class="item-row">
      <td><button id="delete" href="javascript:;" onclick="deleteRow(this)" title="Remove row">Delete</button></td>
      <td><input class="form-control row-desc" id="desc" rows="1"></td>
      <td><input class="form-control tx-right row-qty" type="text" id="qty" onkeyup="calc()" value="0"></td>
      <td><input class="form-control tx-right row-unitprice" type="text" id="unitprice" value="0"></td>
      <td><input class="form-control tx-right row-amount" type="text" id="amount" disabled></td>
      <td>
        <input class="form-control tx-right row-tax" type="text" id="amounttax"></td>
    </tr>
   
  </tbody>
  <tr id="hiderow">
    <td colspan="7" class="tx-center tx-15"><b><a id="addrow" href="javascript:;" title="Add a row"><i class="fe fe-plus-circle"></i>Add an Item</a></b></td>
  </tr>
</table>
<br><br>


        $(document).ready(function() {
          AddItem();
          $('#addrow').click(function() {
            addItem();
          });
          $('.delete-row').click(function() {
            deleteRow(btn);
          });
                      $('#qty').on('keyup', 'input', function () {
                inputs = $(this).parents('tr');
                calc(inputs); 
            });
        });

        function deleteRow(btn) {
          var row = btn.parentNode.parentNode;
          var next = row.parentNode.rows[row.rowIndex + 0];
          row.parentNode.removeChild(next);
          row.parentNode.removeChild(row);
        }

        function addItem() {

          var itemRow =
            `<tr class="item-row">
            <td><button class="delete-row" href="javascript:; "onclick = "deleteRow(this)">Delete</button></td>
            <td><textarea class="form-control row-desc" id="desc" rows="1"></textarea></td> 
            <td><input class="form-control tx-right row-qty" type="text" id="qty" onkeyup="calc()" value="0"></td>
            <td><input class="form-control tx-right row-unitprice" type="text" id="unitprice" value="0"></td>
            <td><input class="form-control tx-right row-amount" type="text" id="amount" disabled></td>
          <td><input class="form-control tx-right row-tax" type="text" id="amounttax"></td>
            </tr>` ;

          $(".items_table").append(itemRow);

        }

        function AddItem() {
          $("#btnAddItem").click(function(e) {
            //arrayItem
            var arrayItem = [];
            var sArrayItem = "";

        $.each($(".items_table .item-row"),function(index,value){

        let desc = $(this).find(".row-desc").val()
        let qty = $(this).find(".row-qty").val()
        let unitprice = $(this).find(".row-unitprice").val()
        let amount = $(this).find(".row-amount").val()
        let tax = $(this).find(".row-tax").val()
        let item = {
          ItemDesc: desc,
          ItemUnitPrice:unitprice,
          ItemQty: qty,
          TaxAmount: tax,
          ItemTotalAmount: amount,
        }
        arrayItem.push(item)
        });
            sArrayItem = JSON.stringify(arrayItem);

            $.ajax({
              type: "POST",
              url: "AddItem",
              data: JSON.stringify({
                sArrayItem
              }),
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function(result) {

                if (result.d.indexOf(".aspx") != -1)
                  window.location.href = result.d;
                else
                  showPopup(result);
              },
              failure: function(response) {
                alert(response.d);
              }
            });
          });
        };
        function calc(inputs) {

            //get all of the various input typs from the rows
            //each will be any array of elements
            var Quantitys = $('.row-qty');
            var UnitPrices = $('.row-unitprice');
            var Amounts = $('.row-amount');

//at result, I only able auto prompt the first row, he second row onwards it does not auto prompt the amount when user enter qty & unitprice.
            $.each($(".items_table .item-row"),function (i, value) {

                // get all the elements for the current row
                var Quantity = $(this).find('.row-qty').val();
                var UnitPrice = $(this).find('.row-unitprice').val();
                var Amount = $(this).find('.row-amount').val();
               
                ////// get the needed values from this row
                var qty = Quantity.val();
                qty = qty == '' ? 0 : qty; // if blank default to 0
                Quantity.val(qty); // set the value back, in case we had to remove soemthing
                var price = UnitPrice.val();
                price = price == '' ? 0 : price; // if blank default to 0
                UnitPrice.val(price); // set the value back, in case we had to remove soemthing

                // get/set row tax and total
                // also add to our totals for later
                var rowPrice = (UnitPrice * 1000) * Quantity
                var total = rowPrice

                Amount.val((total / 1000).toFixed(2));

            });

        }

【问题讨论】:

标签: jquery asp.net


【解决方案1】:

你在数据和选择器之间做了很多混合:

按照您的代码,仅当您将某些内容放入 Quantity(keyup 函数)时才会计算金额:

$(document).ready(function() {
  AddItem();
  $('#addrow').click(function() {
    addItem();
  });
  $('.delete-row').click(function() {
    deleteRow(btn);
  });
  $('#qty').on('keyup', 'input', function() {
    inputs = $(this).parents('tr');
    calc(inputs);
  });
});

function deleteRow(btn) {
  var row = btn.parentNode.parentNode;
  var next = row.parentNode.rows[row.rowIndex + 0];
  row.parentNode.removeChild(next);
  row.parentNode.removeChild(row);
}

function addItem() {

  var itemRow =
    `<tr class="item-row">
            <td><button class="delete-row" href="javascript:; "onclick = "deleteRow(this)">Delete</button></td>
            <td><textarea class="form-control row-desc" id="desc" rows="1"></textarea></td> 
            <td><input class="form-control tx-right row-qty" type="text" id="qty" onkeyup="calc()" value="0"></td>
            <td><input class="form-control tx-right row-unitprice" type="text" id="unitprice" value="0"></td>
            <td><input class="form-control tx-right row-amount" type="text" id="amount" disabled></td>
          <td><input class="form-control tx-right row-tax" type="text" id="amounttax"></td>
            </tr>`;

  $(".items_table").append(itemRow);

}

function AddItem() {
  $("#btnAddItem").click(function(e) {
    //arrayItem
    var arrayItem = [];
    var sArrayItem = "";

    $.each($(".items_table .item-row"), function(index, value) {

      let desc = $(this).find(".row-desc").val()
      let qty = $(this).find(".row-qty").val()
      let unitprice = $(this).find(".row-unitprice").val()
      let amount = $(this).find(".row-amount").val()
      let tax = $(this).find(".row-tax").val()
      let item = {
        ItemDesc: desc,
        ItemUnitPrice: unitprice,
        ItemQty: qty,
        TaxAmount: tax,
        ItemTotalAmount: amount,
      }
      arrayItem.push(item)
    });
    sArrayItem = JSON.stringify(arrayItem);

    $.ajax({
      type: "POST",
      url: "AddItem",
      data: JSON.stringify({
        sArrayItem
      }),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(result) {

        if (result.d.indexOf(".aspx") != -1)
          window.location.href = result.d;
        else
          showPopup(result);
      },
      failure: function(response) {
        alert(response.d);
      }
    });
  });
};

function calc(inputs) {

  //get all of the various input typs from the rows
  //each will be any array of elements
  var Quantitys = $('.row-qty');
  var UnitPrices = $('.row-unitprice');
  var Amounts = $('.row-amount');

  $.each($(".items_table .item-row"), function(i, value) {

    // get all the elements for the current row
    var Quantity = $(this).find('.row-qty');
    var UnitPrice = $(this).find('.row-unitprice');
    var Amount = $(this).find('.row-amount');

    ////// get the needed values from this row
    var qty = Quantity.val();
    qty = qty == '' ? 0 : qty; // if blank default to 0
    Quantity.val(qty); // set the value back, in case we had to remove soemthing
    var price = UnitPrice.val();
    price = price == '' ? 0 : Number(price); // if blank default to 0
    UnitPrice.val(price); // set the value back, in case we had to remove soemthing

    // get/set row tax and total
    // also add to our totals for later
    var rowPrice = price * 1000 * qty;
    var total = rowPrice;

    Amount.val((total / 1000).toFixed(2));

  });

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Action</th>
      <th>Description</th>
      <th>Qty</th>
      <th>Unit Price</th>
      <th>Amount</th>
      <th>Tax</th>
    </tr>
  </thead>
  <tbody class="items_table">
    <tr class="item-row">
      <td><button id="delete" href="javascript:;" onclick="deleteRow(this)" title="Remove row">Delete</button></td>
      <td><input class="form-control row-desc" id="desc" rows="1"></td>
      <td><input class="form-control tx-right row-qty" type="text" id="qty" onkeyup="calc()" value="0"></td>
      <td><input class="form-control tx-right row-unitprice" type="text" id="unitprice" value="0"></td>
      <td><input class="form-control tx-right row-amount" type="text" id="amount" disabled></td>
      <td>
        <input class="form-control tx-right row-tax" type="text" id="amounttax"></td>
    </tr>

  </tbody>
  <tr id="hiderow">
    <td colspan="7" class="tx-center tx-15"><b><a id="addrow" href="javascript:;" title="Add a row"><i class="fe fe-plus-circle"></i>Add an Item</a></b></td>
  </tr>
</table>
<br><br>
<button id="btnAddItem">Create Array</button>

【讨论】:

  • 这样我比较容易理解,非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多