实现表格自动计算
每一行进行小计,数量 X 单价。而总计则是把表格中小计列所有行进行相加。
Html code:
<table id="Order"> <tr> <th>费用名目</th> <th>数量</th> <th>单价</th> <th>小计</th> </tr> <tr class="trData"> <td>ItemA</td> <td><input type="text" class='txtQuantity' /></td> <td><input type="text" class='txtPrice' /></td> <td><input type="text" class='txtAmount' /></td> </tr> <tr class="trData"> <td>ItemB</td> <td><input type="text" class='txtQuantity' /></td> <td><input type="text" class='txtPrice' /></td> <td><input type="text" class='txtAmount' /></td> </tr> <tr class="trData"> <td>ItemC</td> <td><input type="text" class='txtQuantity' /></td> <td><input type="text" class='txtPrice' /></td> <td><input type="text" class='txtAmount' /></td> </tr> <tr class="trData"> <td colspan="3" style="text-align:right;">总计</td> <td><span id="total"></span></td> </tr> </table>
jQuery code:
CalcSum(); function CalcSum() { var total_sum = 0; $("#Order .txtAmount").each(function () { var val = $(this).val(); if ($.isNumeric(val)) { total_sum += parseFloat(val); } }); $("#total").html(total_sum); }
jQuery code:
$("#Order").on('input', '.txtQuantity', function () { var self = $(this); var tr = self.closest("tr"); var quantity = self.val(); var Price = tr.find(".txtPrice").val(); var amount = 0 if ($.isNumeric(quantity) && $.isNumeric(Price)) { amount = quantity * Price; } tr.find(".txtAmount").val(amount); CalcSum(); });
jQuery code:
$("#Order").on('input', '.txtPrice', function () { var self = $(this); var tr = self.closest("tr"); var quantity = tr.find(".txtQuantity").val(); var Price = self.val(); var amount = 0 if ($.isNumeric(quantity) && $.isNumeric(Price)) { amount = quantity * Price; } tr.find(".txtAmount").val(amount); calcSum(); });