基于jQuery实现自动价格计算与手动折扣功能的HTML页面开发需求
Simplest jQuery Implementation for Your Calculation Table
Here's a clean, minimal solution to add the automatic calculations you need. I'll adjust your HTML to use meaningful classes/IDs (so jQuery can target elements easily) and write concise code to handle all the math:
Modified HTML
First, update your HTML to include classes for item inputs and IDs for total fields. I've made non-editable fields readonly to prevent manual changes:
<table width="300" border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td>Item Name</td> <td>Qty</td> <td>Price(Per/Kg)</td> <td>Amount</td> </tr> <tr> <td>Test Item 1</td> <td><input type="text" class="qty" /></td> <td><input type="text" class="price" /></td> <td><input type="text" class="amount" readonly /></td> </tr> <!-- Add more item rows here with the same classes --> </tbody> </table> <p> </p> <table width="300" border="0"> <tr> <td width="100"><strong>Total Amount</strong></td> <td><input type="text" id="total-amount" readonly /></td> </tr> <tr> <td><strong>Discount</strong></td> <td><input type="text" id="discount" /></td> </tr> <tr> <td><strong>Net Amount</strong></td> <td><input type="text" id="net-amount" readonly /></td> </tr> </table>
jQuery Code
Add this script (make sure you've included jQuery in your page first, e.g., via <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>):
$(document).ready(function() { // Calculate amount for a single item row const calculateAmount = (row) => { const qty = parseFloat(row.find('.qty').val()) || 0; const price = parseFloat(row.find('.price').val()) || 0; const amount = qty * price; row.find('.amount').val(amount.toFixed(2)); calculateTotal(); }; // Sum all amounts to get total const calculateTotal = () => { let total = 0; $('.amount').each((_, el) => total += parseFloat(el.value) || 0); $('#total-amount').val(total.toFixed(2)); calculateNet(); }; // Calculate net amount (total minus discount) const calculateNet = () => { const total = parseFloat($('#total-amount').val()) || 0; const discount = parseFloat($('#discount').val()) || 0; $('#net-amount').val((total - discount).toFixed(2)); }; // Listen for input changes on quantity/price fields $('.qty, .price').on('input', function() { calculateAmount($(this).closest('tr')); }); // Listen for discount changes $('#discount').on('input', calculateNet); });
Key Features:
- Real-time Updates: Uses the
inputevent so calculations refresh as the user types (no waiting for them to leave the field). - Error Resilience: Treats empty inputs as
0to avoid NaN errors. - Currency Formatting: Uses
toFixed(2)to display values as standard currency (adjust the number if you need more/less decimal places). - Scalable: Add more item rows with the same
.qty,.price,.amountclasses and the code will automatically include them in the total.
内容的提问来源于stack exchange,提问作者Ajitsree
相关产品推荐
相关产品推荐

