如何从动态生成表格中获取带[$i]后缀的元素ID对应的值并完成金额计算
实现方案
你可以通过触发元素定位到当前行,再匹配对应输入框的方式实现,不需要拼接带[$i]的ID,兼容性更强,修改步骤如下:
第一步:修正HTML模板的两处问题
- 所有触发
kofta函数的onchange事件都传入当前元素this - 删除
newq[$i]ID后多余的空格,避免选择器匹配失败
修改后的PHP输出的行代码片段:
<?php for ($i = 1; $i <= 2; $i++) { echo " <tr> <td align='center'><?php echo $i;?></td> <td><input type='text' class='form-control ' value='' id='itemname[$i]' /></td> <td><input type='text' class='form-control num-only ' id='price[$i]' onchange='kofta(this)' /></td> <td><input type='number' class='form-control num-only' maxlength='5' id='quantity[$i]' onchange='kofta(this)'/></td> <td><input type='text' class='form-control num-only' maxlength='50' id='inStore[$i]' onchange='kofta(this)'/></td> <td><input type='text' class='form-control num-only' maxlength='10' id='newq[$i]' onchange='kofta(this)'/></td> <td><input type='text' class='form-control num-only' maxlength='50' id='total[$i]' readonly /></td> </tr> "; } ?>
第二步:重写kofta函数
function kofta(el) { // 1. 定位当前触发元素所在的行 const currentRow = el.closest('tr'); // 2. 获取当前行的单价、数量值,空值默认转0 const price = parseFloat(currentRow.querySelector('input[id^="price["]').value) || 0; const quantity = parseInt(currentRow.querySelector('input[id^="quantity["]').value) || 0; // 3. 计算单行小计,保留2位小数 const rowTotal = (price * quantity).toFixed(2); currentRow.querySelector('input[id^="total["]').value = rowTotal; // 4. 计算全局总计 let allTotal = 0; document.querySelectorAll('input[id^="total["]').forEach(totalInput => { allTotal += parseFloat(totalInput.value) || 0; }); document.getElementById('total').value = allTotal.toFixed(2); }
实现说明
- 用
closest('tr')直接定位当前输入框所在的行,不需要手动拼接带[$i]的ID,后续如果动态新增/删除行也可以正常工作 - 选择器
input[id^="price["]表示匹配ID以price[开头的输入框,自动适配不同的$i后缀 - 加入了空值、非数字值的兼容处理,避免计算出现NaN
内容的提问来源于stack exchange,提问作者Wesam Beshir
相关产品推荐
相关产品推荐

