如何使用jquery动态添加行和计算总和

时间:2014-12-22 12:06:01

标签: javascript jquery html

我正在尝试动态地将行添加到html表中以使用jquery生成帐单。我想在添加或删除行时动态计算总计

我的代码

这些是我从中获取值的输入字段。所有DropDown框都从DB填充。

<div class="block-fluid">                        

                        <div class="row-form clearfix">
                            <div class="span3">Select Product:</div>
                            <div class="span7">
                                <select name="selectprod" id="s2_2" style="width: 100%;">
                                    <option value="0">Choose a Product...</option>
                                   <optgroup id="Tablets" label="Tablets">

                                   </optgroup>
                                   <optgroup id="Capsule" label="Capsule">

                                   </optgroup>
                                   <optgroup id="Syrup" label="Syrup">

                                   </optgroup> 
                                   <optgroup id="Drops" label="Drops">

                                   </optgroup>
                                   <optgroup id="Inhalers" label="Inhalers">

                                   </optgroup>
                                   <optgroup id="Topical" label="Topical">

                                   </optgroup>
                                   <optgroup id="Intravascular" label="Intravascular">

                                   </optgroup>
                                </select>
                            </div>
                        </div>           
                        <div class="row-form clearfix" id="prodnamediv">
                             <div class="span3">Product Name:</div>
                             <div class="span7">
                             <input id="prodnameinput" type="text" value="" readonly="readonly"/>
                             </div>
                        </div>
                        <div class="row-form clearfix" id="prodcompdiv">
                             <div class="span3">Product Company:</div>
                             <div class="span7">
                             <input id="prodcompinput" type="text" value="" readonly="readonly"/>
                             </div>
                        </div>
                        <div class="row-form clearfix" id="prodtypediv">
                             <div class="span3">Product Type:</div>
                             <div class="span7">
                             <input id="prodtypeinput" type="text" value="" readonly="readonly"/>
                             </div>
                        </div>
                        <div class="row-form clearfix" id="proddosediv">
                             <div class="span3">Product Dose:</div>
                             <div class="span7">
                             <input id="proddoseinput" type="text" value="" readonly="readonly"/>
                             </div>
                        </div>
                        <div class="row-form clearfix" id="tabletdiv">
                             <div class="span3">Tablets Per Strip:</div>
                             <div class="span7">
                             <input id="tabletinput" type="text" value="" readonly="readonly"/>
                             </div>
                        </div>
                        <div class="row-form clearfix" id="prodcapacitydiv">
                             <div class="span3">Product Capacity:</div>
                             <div class="span7">
                             <input id="prodcapacityinput" type="text" value="" readonly="readonly"/>
                             </div>
                        </div>
                        <div class="row-form clearfix" id="currentstockdiv">
                             <div class="span3">Current Stock Quantity:</div>
                             <div class="span7">
                             <input id="currentstockinput" type="text" value="" readonly="readonly"/>
                             </div>
                        </div>
                        <div class="row-form clearfix" id="prodpricetabcapdiv">
                             <div class="span3">Price Per Tablet/Capsule:</div>
                             <div class="span7">
                             <input id="prodpricetabcapinput" type="text" value="" />
                             </div>
                        </div>
                        <div class="row-form clearfix" id="prodpricediv">
                             <div class="span3">Product Price:</div>
                             <div class="span7">
                             <input id="prodpriceinput" type="text" value="" />
                             </div>
                        </div>
                        <div class="row-form clearfix" id="qtytoselldiv">
                             <div class="span3">No. of Quantities to sell:</div>
                             <div class="span7">
                             <input id="qtytosellinput" type="text" value="" />
                             </div>
                        </div>
                        <div class="row-form clearfix" id="tablettoselldiv">
                             <div class="span3">No. of Tablets/Capsules to sell:</div>
                             <div class="span7">
                             <input id="tablettosellinput" type="text" value="" />
                             </div>
                        </div>
                        <div class="row-form clearfix" id="pkgdatediv">
                             <div class="span3">Packaging Date:</div>
                             <div class="span7">
                             <input id="pkgdateinput" type="text" value="" />
                             </div>
                        </div>
                        <div class="row-form clearfix" id="manufactdiv">
                             <div class="span3">Manufacturing Date:</div>
                             <div class="span7">
                             <input id="manufactinput" type="text" value="" />
                             </div>
                        </div>
                        <div class="row-form clearfix" id="expdatediv">
                             <div class="span3">Expiry Date:</div>
                             <div class="span7">
                             <input id="expdateinput" type="text" value="" />
                             </div>
                        </div>
                        <div class="row-form clearfix" id="batchnodiv">
                             <div class="span3">Batch No.:</div>
                             <div class="span7">
                                <select name="select" id="s2_1" style="width: 100%;">
                                    <option value="0">choose a option...</option>                             
                                </select>
                            </div>
                        </div>
                        <div class="toolbar clearfix">
                            <div class="right">
                                <div class="btn-group">
                                     <button class="btn" id="addtopurchase" type="button" value="Add"><span>Add</span></button>
                                </div>
                            </div>
                        </div> 
                    </div>

这是我的表格,当按下“添加”按钮时动态填充

<div class="block-fluid table-sorting clearfix">
                        <table cellpadding="0" cellspacing="0" width="100%" class="table" id="tSortable_2">
                            <thead>
                                <tr>
                                    <th width="20%">Product</th>
                                    <th width="12%">Pkg Date</th>
                                    <th width="12%">Mfact date</th>
                                    <th width="12%">Expiry</th>
                                    <th width="12%">Batch No.</th>
                                    <th width="12%">Unit Price</th>
                                    <th width="10%">Qty</th>
                                    <th width="10%">Subtotal</th>  
                                    <th></th>                                  
                                </tr>
                            </thead>
                            <tbody id="tablebody">
                               <tr>
                         <td class="prodname">prod</td>
                         <td class="pkgdate">pkgdate</td>
                         <td class="manufactdate">manufactdate</td>
                         <td class="expdate">expdate</td>
                         <td class="batchno">batchno</td>
                         <td class="unitprice">pertabprice</td>
                         <td class="qty">qty</td>
                         <td class="subtot">subtotal</td>
                         <td>
                            '<button class="btn btn-link" type="button">Remove</button>
                        </td>
                     </tr>
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td></td>
                                    <td></td>
                                    <td></td>   
                                    <td></td> 
                                    <td></td>
                                    <td></td>
                                    <td>Total:</td>
                                    <td></td>
                                    <td>
                                  <div class="toolbar clear clearfix">
                            <div class="center">                                
                                <button type="button" class="btn btn-small btn-warning"><span class="icon-ok icon-white"></span></button>                                
                            </div>
                        </div>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

此脚本动态填充上表行

<script type="text/javascript">
    $(document).ready(function(){
     $('#addtopurchase').click(function(e){
         alert('Clicked');
         var selected = $('#s2_2 :selected');
         var type = selected.parent().attr('label');
         var prod = $('#s2_2 option:selected').text();
         if(prod != "Choose a Product...")
             {
             alert('In prod');

             if(type == "Tablets" || type == "Capsule")
                 {
                 alert('In tablets');
                 var stock = Number($('#currentstockinput').val());
                 var qty = Number($('#tablettosellinput').val().replace(/[^0-9\.]+/g,""));
                 if(qty < stock)
                 {
                 var pertabprice = Number($('#prodpricetabcapinput').val().replace(/[^0-9\.]+/g,"")).toFixed(2);
                 var subtotal = qty * pertabprice;
                 var pkgdate = $('#pkgdateinput').val();
                 var manufactdate = $('#manufactinput').val();
                 var expdate = $('#expdateinput').val();
                 var batchno = $('#s2_1 option:selected').text();

                 $('#tablebody').prepend('<tr>'+
                         '<td class="prodname">'+prod+'</td>'+
                         '<td class="pkgdate">'+pkgdate+'</td>'+
                         '<td class="manufactdate">'+manufactdate+'</td>'+   
                         '<td class="expdate">'+expdate+'</td>'+ 
                         '<td class="batchno">'+batchno+'</td>'+
                         '<td class="unitprice">'+pertabprice+'</td>'+
                         '<td class="qty">'+qty+'</td>'+
                         '<td class="subtot">'+subtotal+'</td>'+
                         '<td>'+
                            '<button class="btn btn-link" type="button">Remove</button>'+
                        '</td>'+
                     '</tr>');

                 }
                 else
                     {
                     alert('Not enough Stock');
                     }
                 loadgrandtotal();
                 }
             else
                 {

                 var stock = Number($('#currentstockinput').val());
                 var qty = Number($('#qtytosellinput').val().replace(/[^0-9\.]+/g,""));
                 if(qty < stock)
                 {

                 var prodprice = Number($('#prodpriceinput').val().replace(/[^0-9\.]+/g,"")).toFixed(2);

                 var subtotal = qty * prodprice;

                 var pkgdate = $('#pkgdateinput').val();

                 var manufactdate = $('#manufactinput').val();

                 var expdate = $('#expdateinput').val();

                 var batchno = $('#s2_1 option:selected').text();

                 $('#tablebody').prepend('<tr>'+
                         '<td class="prodname">'+prod+'</td>'+
                         '<td class="pkgdate">'+pkgdate+'</td>'+
                         '<td class="manufactdate">'+manufactdate+'</td>'+   
                         '<td class="expdate">'+expdate+'</td>'+ 
                         '<td class="batchno">'+batchno+'</td>'+
                         '<td class="unitprice">'+prodprice+'</td>'+
                         '<td class="qty">'+qty+'</td>'+
                         '<td class="subtot">'+subtotal+'</td>'+
                         '<td>'+
                            '<button class="btn btn-link" type="button">Remove</button>'+
                        '</td>'+
                     '</tr>');

                 }
                 else
                     {
                     alert('Not enough Stock');
                     }
                 }
             loadgrandtotal();
             }
         else
             {

             }

     })

    });
    </script>

这是问题所在。此脚本应计算所有小计并生成总计 但是这个脚本似乎不起作用,我无法弄清楚原因。 td值从类“.subtot”中读取,该类与td相关联,并使用上面的脚本动态生成

     <script type="text/javascript">
         function loadgrandtotal()
         {
var sum=0;
var prodprice = 0;
             $('#tSortable_2 tbody tr').each(function() {
                var prodprice = Number($(this).find(".subtot").text()).toFixed(2);  
                sum = sum + prodprice;
             });

         }
        </script>

4 个答案:

答案 0 :(得分:1)

为什么不直接在subtot类上进行循环。

您还需要确保在将toFixed添加到sum之前不要调用function loadgrandtotal() { var sum = 0; $('.subtot').each(function () { var prodprice = Number($(this).text()); sum = sum + prodprice; }); $("#total").text(sum.toFixed(2)); } ,因为这会导致字符串连接。最后这样做,就像这样:

{{1}}

Here is a working example

答案 1 :(得分:0)

您不应迭代元素来计算总和,而是使用Object来保存和呈现您购买的数据。我已经为您提供了一个示例代码,您可以运行该代码来获取事物

<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>

function PurchaseTable(elementId){

this.containerElement = $('#' + elementId);
this.purchasedItems = [];
this.totalAmount = 0;

this._initializeTableLayout();

}

PurchaseTable.prototype.addItem = function(purchasedItem){
this.purchasedItems.push(purchasedItem);    
this.totalAmount += purchasedItem.subTotal;
this._addtoTable(purchasedItem);
}

PurchaseTable.prototype._addtoTable = function(purchasedItem){

var itemHtml = '<tr><td>' + purchasedItem.subTotal +'</td></tr>';//construct the layout of the purchased Item with all the data in here

this.containerElement.find('#tableBody').prepend(itemHtml);
this.containerElement.find('#total').html(this.totalAmount);
}

PurchaseTable.prototype._initializeTableLayout = function(){

var tableHtml = "<table><thead><tr><th>Column1</th></tr></thead><tbody id='tableBody'><tr><td id='total'>0</td></tr></tbody></table>";//PLace HTML of table with headers and empty table body in here

this.containerElement.html(tableHtml);

}

</script>

<script>

var purchases = null;

function initPurchases(){

purchases = new PurchaseTable('container');
}

function addItem(){

purchases.addItem({id:1, subTotal:10});

}

</script>
</head>
<body onload="initPurchases();">

<div id="container"></div>
<button onclick="addItem();">Add Item</button>
</body>
</html>

答案 2 :(得分:-1)

function loadgrandtotal()
             {

              var prodprice=0;
                 $('#tablebody tr').each(function() {
                    prodprice =prodprice + Number($(this).find(".subtot").text()).toFixed(2);  

                 });

             }

答案 3 :(得分:-2)

那是因为$('#tSortable_2 tbody tr').each执行一次而不是动态执行。这意味着,它仅在调用loadgrandtotal时执行,而不是每次创建新行时执行。相反,您需要确保每个函数运行时都包含新行。要做到这一点,你需要确保loadgrandtotal以某种方式运行多次(我会通过在添加价格时运行它来实现)。

$('.priceInput').on('change', loadgrandtotal);

N.B:小心进行十进制计算。将价格转换为整数然后将它们转换为十进制值非常重要。