计算表中动态添加的项的总和 [英] Calculate total sum of dynamically added items to a table

查看:73
本文介绍了计算表中动态添加的项的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 itemPrice *数量字段计算每个项目的行总数,该行金额将自动填充在 linePrice 文本框中.然后,通过汇总所有线价,将总计自动填充到 priceTotal 字段中.

I would like to calculate the line total for each item using the itemPrice* Qty fields, the line amount is to be auto populated in the linePrice textbox. After which the grand total is then auto populated to the priceTotal field by summing up all the line prices.

我很难将每个 Qty itemPrice 文本框值添加到我的JavaScript函数中,因为名称是 Qty0,Qty1,Qty2 ... itemPrice0,itemPrice1 .... ,具体取决于添加的行,并将最终计算结果输入相应的文本框中.

I am having a challenge getting each Qty and itemPrice textbox value into my JavaScript function since the name(s) is/are Qty0, Qty1, Qty2... and itemPrice0, itemPrice1,.. depending on the added row, and also getting the final calculations into the respective textboxes.

下面是我的代码.

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
    return false;
  return true;
}


$(document).ready(function() {
  $(document).on("keyup", ".Qty", calculateTot);
  $("button").click(function() {
    addrow('tb')
  });
});

function calculateTot() {

  var sum = 0;
  var price = document.getElementById('itemPrice').value;
  var qtyPur = parseFloat(this.value);

  $(".Qty").each(function() {

    if (!isNaN(this.value) && this.value.length != 0) {
      linePR = price * qtyPur;
    }

  });
  $("#linePrice").val(linePR.toFixed(2));
  calculateSum();
}


function calculateSum() {

  var sum = 0;
  $(".linePrice").each(function() {

    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }

  });
  $("#priceTotal").val(sum.toFixed(2));
}

$(document).ready(function() {
  var i = 1,
    j = 1;
  $("#add_row").click(function() {
    if (i < 10) {
      $('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");

      $('#tab_add').append('<tr id="addr' + (i + 1) + '"></tr>');
      i++;
      j++;
      $('#delete_row').show();
    } else {
      alert("You can only add upto a maximum of 10 items")
      $('#add_row').hide();
    }
  });
  $("#delete_row").click(function() {
    if (i > 1) {
      var r = confirm('Do you want to delete this item?');
      if (r == true) {
        $("#addr" + (i - 1)).html('');
        i--;
        $('#add_row').show();
      }
    } else {
      alert("Entry cannot be deleted")
      $('#delete_row').hide();
    }

  });
});

 <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
    <script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<table class="table table-bordered table-hover" id="tab_add">
  <tbody>
    <tr>
      <td colspan="2"><b>Customer Name</b></td>
      <td colspan="1">
        <select name="Per_Name[]" class="form-control">
          <option value="">Select Customer</option>
          <option value="2000001">John Doe</option>
          <option value="2000002">Jane Doe</option>
          <option value="2000003">Tom Harry</option>
          <option value="2000004">Steve Jobs</option>
        </select>
      </td>
    </tr>
    <tr id='addr0'>
      <td><b>1</b></td>
      <td><b>Select Item</b></td>
      <td colspan="1">
        <select name="Sub_Name[]" class="form-control">
          <option value="">Select Item</option>
          <option value="1000001">Item A</option>
          <option value="1000002">Item B</option>
          <option value="1000003">Item C</option>
          <option value="1000004">Item D</option>
        </select>
      </td>
      <td><input type="text" name="itemPrice0" id="itemPrice0" class="itemPrice form-control" placeholder="Unit Price"></td>
      <td><input type="number" name="Qty0" id="Qty0" class="Qty form-control" onkeypress="return isNumberKey(event)" placeholder="Quantity"></td>
      <td><input type="text" name="linePrice0" id="linePrice0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
      <th>
        <a href="javascript:void(0);" style="font-size:18px;width:33%;" id="add_row" title="Add More Item"><span class="glyphicon glyphicon-plus"></span></a>
        <a href="javascript:void(0);" style="font-size:18px;width:33%;" id="delete_row" title="Remove Item"><span class="glyphicon glyphicon-minus"></span></a>
      </th>
    </tr>
    <tr id='addr1'></tr>
  </tbody>
</table>
<table class="table table-bordered table-hover">
  <tr id="finRow">
    <td colspan="2" width="75%"><b>TOTAL</b></td>
    <td><input type="text" name="priceTotal" id="priceTotal" class="row-total form-control" disabled></td>
  </tr>
</table>

推荐答案

为减少完成此操作所需的DOM遍历量,建议您将data-*属性添加到元素中,以便获得索引并使用它直接引用其他元素.

In order to reduce the amount of DOM traversal that you have to do to accomplish this, I suggest adding data-* attributes to your elements so that you can get the index and use that to reference the other elements directly.

<td><input type="text" name="itemPrice0" id="itemPrice0" data-index="0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" data-index="0" class="Qty form-control" onkeypress="if(!isNumberKey(event)){return false;}" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" data-index="0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>

然后在您的$("#add_row").click(function() {函数中,在创建新元素时添加data-index='"+j+"' ...

Then in your $("#add_row").click(function() { function we add data-index='"+j+"' when creating the new elements ...

$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' data-index='"+j+"' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' data-index='"+j+"' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' data-index='"+j+"' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");

最后,将您的keyup处理程序更改为...

Finally, change your keyup handler to ...

$("#tab_add").on("keyup", ".Qty", function(e){

    var qtyPur = parseFloat(this.value);

    if (!isNaN(this.value) && this.value.length != 0) {

        // this is where use use the data-index attribute to dynamically generate the target element ids
        $("#linePrice"+$(this).data('index')).val(
            parseFloat($("#itemPrice"+$(this).data('index')).val()) * qtyPur
        );
     }

    calculateSum()

});

参见演示

这篇关于计算表中动态添加的项的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆