You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML动态表格行总计求和与付款余额计算功能开发求助

Solution for Calculating Grand Total and Balance

Let's tackle your two requirements smoothly, integrating the new functions with your existing code. Here's the complete implementation with clear explanations:

Step 1: Calculate Grand Total of All Rows

First, we'll add a function to compute the sum of every row's Total value and update the totalamount input. We'll trigger this function whenever a row's quantity/cost changes or a new row is added to keep the total in sync.

Step 2: Calculate G.T. Balance

Next, we'll build a function that subtracts the paid amount (from total10) from the grand total and updates the gtotal input. This will run automatically whenever the paid amount is modified.

Complete JavaScript Code

let x = 0;

function additem() {
    x++;
    var html = `<tr>
        <td><center>${x}</center></td>
        <td><input type='text' class='form-control' name='product_name'></td>
        <td><input type='text' class='form-control' name='batch_no'></td>
        <td><input type='text' class='form-control' name='remarks'></td>
        <td><input id='qty${x}' type='number' class='form-control' oninput='calculate(${x})' name='total_qty'></td>
        <td><input id='cost${x}' type='number' class='form-control' oninput='calculate(${x})' name='cost'></td>
        <td><input type='number' class='form-control' id='total${x}' name='total' readonly></td>
        <td><button type='button' id='btn' class='btn btn-danger' onclick='removeRow(this)'><i class='fa fa-remove'></i></button></td>
    </tr>`;
    document.getElementById("tbody").insertRow().innerHTML = html;
    // Update grand total right after adding a new row
    calculateGrandTotal();
}

function calculate(x) {
    const qty = parseFloat(document.getElementById(`qty${x}`).value) || 0;
    const cost = parseFloat(document.getElementById(`cost${x}`).value) || 0;
    const totalElem = document.getElementById(`total${x}`);
    totalElem.value = qty * cost;
    // Refresh grand total whenever a row's total changes
    calculateGrandTotal();
}

// Compute and update the overall grand total
function calculateGrandTotal() {
    let grandTotal = 0;
    // Grab all inputs with IDs starting with 'total'
    const totalElements = document.querySelectorAll('[id^="total"]');
    totalElements.forEach(element => {
        // Skip non-row-total inputs (totalamount, total10, gtotal)
        if (!['totalamount', 'total10', 'gtotal'].includes(element.id)) {
            grandTotal += parseFloat(element.value) || 0;
        }
    });
    document.getElementById('totalamount').value = grandTotal;
    // Update balance immediately when grand total changes
    calculateBalance();
}

// Calculate and update G.T. Balance
function calculateBalance() {
    const grandTotal = parseFloat(document.getElementById('totalamount').value) || 0;
    const paidAmount = parseFloat(document.getElementById('total10').value) || 0;
    const balance = grandTotal - paidAmount;
    document.getElementById('gtotal').value = balance;
}

// Optional: Add row removal functionality (matches your delete button)
function removeRow(button) {
    const row = button.closest('tr');
    row.remove();
    // Refresh grand total after deleting a row
    calculateGrandTotal();
}

Required HTML Adjustment

Add the oninput event to your total10 input to trigger balance calculations in real-time:

<input type="number" name="paid" id="total10" class="form-control" oninput="calculateBalance()" />

Key Notes

  • Empty Value Handling: We use parseFloat(value) || 0 to treat blank inputs as 0, avoiding NaN errors in calculations.
  • Real-Time Sync: The grand total updates whenever you add/delete a row or modify quantity/cost. The balance updates automatically when either the grand total or paid amount changes.
  • Row Removal: I added an optional delete function to match the remove button in your HTML—this keeps the grand total accurate when rows are deleted.

内容的提问来源于stack exchange,提问作者ahad nadeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:12:48