我需要从小计中计算总计,

时间:2015-01-13 08:49:04

标签: javascript html

我使用表格作发票,动态添加新行和删除行选项,我的代码适用于计算"数量* productprice = tcost"每一行,但我需要从小计计算总计,任何人都可以建议我如何编写代码。 这是我的剧本:

<script>
  (function() {
  "use strict";

 $("table").on("change", "input", function() {
  var row = $(this).closest("tr");
  var qty = parseFloat(row.find(".quantity").val());
  var price = parseFloat(row.find(".productprice").val());
  var tcost = qty * price;
  row.find(".tcost").val(isNaN(tcost) ? "" : tcost);
  });

})();  
</script>

我的桌子:

<table class="table table-bordered inventory" style="width:95%;float:right;">
    <thead>  
        <tr>
            <th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
            <th>S. No</th>
            <th>Product Name</th>
            <th>Item Code</th>
            <th>Quantity</th>
            <th>Price per Quantity</th>
            <th>Total</th>
        </tr>
    </thead>
    <tbody>
        <tr for="input01">
            <td><input type='checkbox' class='case'/></td>
            <td><span id='snum'>1.</span></td>
            <td><input type='text' id='productname_1' name='productname[]' required/></td>
            <td><input type='text' id='itemcode_1' name='itemcode[]' required/></td>
            <td><input type='text' class="quantity" id='quantity_1' name='quantity[]' style="width:165px;"required/></td>
            <td><input type='text' class="productprice" id='productprice_1' name='productprice[]'style="width:165px;" required/></td>
            <td><input type='text' class="tcost" id='tcost_1' name='tcost[]'style="width:165px;" /> </td>
        </tr>
    </tbody>        
</table>
<input type='text' id='total' name='total' placeholder="Total amount" class="total" id="total"style="margin-left: 51px;"/>

2 个答案:

答案 0 :(得分:1)

我为你制作了这个JSFIDDLE。那是你要的吗?

 var totalValue = 0;
     $(document).find(".tcost").each(function(){
         totalValue += parseFloat($(this).val());
     });
     $("#total").val(totalValue);

JSFIDDLE

答案 1 :(得分:0)

 <script>
  (function() {
 function summarize() {
     var total = 0;
     $(".tcost").each(function() {
          total += parseFloat($(this).val());
     });
     $("#total").val(total);
 }
  "use strict";

 $("table").on("change", "input", function() {
  var row = $(this).closest("tr");
  var qty = parseFloat(row.find(".quantity").val());
  var price = parseFloat(row.find(".productprice").val());
  var tcost = qty * price;
  row.find(".tcost").val(isNaN(tcost) ? "" : tcost);
  summarize();
  });

})();  
</script>