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

如何用JS实现QTE与PU自动相乘填充total字段并汇总到指定输入框

实现方案
  • 核心逻辑说明
    1. 由于表格行是动态生成的,需要使用事件委托绑定输入事件,保证后续新增的行也能正常触发计算逻辑
    2. 按行层级查找对应输入框,规避原代码中id重复导致的选择器异常问题
    3. 兼容非数字输入场景,避免计算时出现NaN异常
    4. 单行计算完成后自动触发全局汇总,同时删除行时也会重新计算汇总值,保证数据实时同步

完整实现代码

$(document).ready(function(){
    // 原有的新增行逻辑
    $('#add_btn').on('click', function(){
        var html='';
        html='<tr>';
        html+='<td><input type="text" name="designation[]" class="form-control"></td>';
        html+='<td><input type="text" name="QTE[]" class="form-control"></td>';
        html+='<td><input type="text" name="PU[]" class="form-control"></td>';
        html+='<td><input type="text" class="form-control form-control-lg" name="total[]" readonly ></td>';
        html+='<td><button type="button" class="btn btn-danger remove-btn">-</button></td>';
        html+='</tr>';
        $('tbody').append(html);
    })

    // 全局汇总计算函数
    function calcTotalCommission() {
        let tot = 0;
        document.querySelectorAll('input[name="total[]"]').forEach(item => {
            const val = parseFloat(item.value);
            if (!isNaN(val)) tot += val;
        })
        document.getElementById('Amount_Commission').value = tot;
    }

    // 事件委托:监听所有QTE和PU的输入事件,适配动态新增行
    $(document).on('input', 'input[name="QTE[]"], input[name="PU[]"]', function() {
        // 定位当前输入框所在的行
        const $currentRow = $(this).closest('tr');
        // 获取当前行的QTE和PU值,非数字默认按0处理
        const qte = parseFloat($currentRow.find('input[name="QTE[]"]').val()) || 0;
        const pu = parseFloat($currentRow.find('input[name="PU[]"]').val()) || 0;
        // 计算乘积写入当前行的只读total字段
        const rowTotal = qte * pu;
        // 可根据业务需求调整保留小数位数,不需要保留小数可直接删除.toFixed(2)
        $currentRow.find('input[name="total[]"]').val(rowTotal.toFixed(2));
        // 重新计算全局汇总金额
        calcTotalCommission();
    })

    // 删除行后重新计算汇总
    $(document).on('click', '.remove-btn',function(){
        $(this).closest('tr').remove();
        calcTotalCommission();
    });
});
  • 优化提示
    原代码中多个元素使用了重复id(比如QTE、PU、remove等),不符合HTML规范,上述代码已经将重复的功能id改为class选择器,避免出现未知的选择异常。

内容的提问来源于stack exchange,提问作者Salah Eddine

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:36:03