如何用JavaScript计算表格中非空输入行的合计值(每行计0.5)
实现表格每行非空输入的权重统计
基础实现方案
先给表格结构加上便于JS定位的类名:
<table id="data-table"> <thead> <tr> <th>输入项1</th> <th>输入项2</th> <th>输入项3</th> <th>Total1</th> </tr> </thead> <tbody> <tr class="data-row"> <td><input type="text" class="row-input"></td> <td><input type="text" class="row-input"></td> <td><input type="text" class="row-input"></td> <td class="row-total">0</td> </tr> <!-- 更多数据行直接复制上述结构即可 --> </tbody> </table>
然后编写JavaScript逻辑,监听输入框变化,实时计算每行合计:
// 获取表格内所有输入框 const allInputs = document.querySelectorAll('#data-table .row-input'); // 给每个输入框绑定输入事件,内容变化时触发计算 allInputs.forEach(input => { input.addEventListener('input', calculateRowTotal); }); // 单行合计计算函数 function calculateRowTotal(event) { // 定位当前输入框所在的行 const currentRow = event.target.closest('.data-row'); // 获取该行所有输入框 const rowInputs = currentRow.querySelectorAll('.row-input'); // 统计非空输入数量(自动忽略纯空格的无效输入) let nonEmptyCount = 0; rowInputs.forEach(input => { if (input.value.trim() !== '') { nonEmptyCount++; } }); // 计算权重总和:非空数量 × 0.5 const total = nonEmptyCount * 0.5; // 更新该行合计单元格,保留一位小数(可按需调整) currentRow.querySelector('.row-total').textContent = total.toFixed(1); }
多合计列的扩展方案
如果需要区分不同组的输入项,分别统计到Total1、Total2等不同单元格,可以给输入项添加分组类:
<tr class="data-row"> <td><input type="text" class="row-input group-1"></td> <td><input type="text" class="row-input group-1"></td> <td><input type="text" class="row-input group-2"></td> <td><input type="text" class="row-input group-2"></td> <td class="total-group-1">0</td> <!-- 对应group1的合计 --> <td class="total-group-2">0</td> <!-- 对应group2的合计 --> </tr>
对应的JS逻辑调整为:
const allInputs = document.querySelectorAll('#data-table .row-input'); allInputs.forEach(input => { input.addEventListener('input', calculateGroupTotals); }); function calculateGroupTotals(event) { const currentRow = event.target.closest('.data-row'); // 计算group1的合计 const group1Inputs = currentRow.querySelectorAll('.row-input.group-1'); let count1 = 0; group1Inputs.forEach(input => { if (input.value.trim() !== '') count1++; }); currentRow.querySelector('.total-group-1').textContent = (count1 * 0.5).toFixed(1); // 计算group2的合计 const group2Inputs = currentRow.querySelectorAll('.row-input.group-2'); let count2 = 0; group2Inputs.forEach(input => { if (input.value.trim() !== '') count2++; }); currentRow.querySelector('.total-group-2').textContent = (count2 * 0.5).toFixed(1); }
关键细节说明
closest('.data-row'):快速定位当前输入框所在的行,比逐层查找父元素更高效。trim():过滤输入框中只有空格的无效内容,避免误统计。toFixed(1):根据需求控制小数位数,不需要的话直接使用total即可。
内容的提问来源于stack exchange,提问作者Abrocodabra
相关产品推荐
相关产品推荐

