如何实现表格每行输入项的总计计算?当前仅第一行生效
问题修复方案
你当前的核心问题是重复使用了全局唯一的ID:HTML里的partialqty、grpoprice、grpototal这些ID在每行都重复定义,而浏览器规定ID必须全局唯一,导致jQuery选择器只会选中第一行的元素,所以只有第一行的总计计算生效。
第一步:修改HTML,替换重复ID为Class
把行内所有重复的ID换成Class,同时移除tr上的重复ID(ID不能复用):
<tr class="grpoTable Tr"> <td>'.$list['item'].'<input type="hidden" value="'.$list['item'].'" name="item[]"></td> <td>'.$list['item_code'].'<input type="hidden" value="'.$list['item_code'].'" name="item_code[]"></td> <td>'.$list['qty'].'<input type="hidden" value="'.$list['qty'].'" name="qty[]"></td> <td><input type="number" jAutoCalc="{partialqty}" class="form-control partialqty" name="partialqty[]" min=1></td> <td>'.$list['unit_price'].'<input type="hidden" jAutoCalc="{grpoprice}" class="grpoprice" value="'.$list['unit_price'].'" name="unit_price[]"></td> <td><span class="grpototal" jAutoCalc="{partialqty}*{grpoprice}"></span></td> <td><button class="btn btn-danger removeGRPO" type="button"><i class="uil uil-multiply"></i></button></td> </tr>
第二步:修改jQuery代码,基于当前行单独计算
将事件绑定到每个数量输入框,通过closest()定位当前所在行,只对该行内的元素进行计算:
$(document).on('keyup', '.partialqty', function() { // 获取当前输入框所在的表格行 var $currentRow = $(this).closest('.grpoTable'); // 从当前行内提取数量和价格(处理空值避免NaN) var qty = parseFloat($currentRow.find('.partialqty').val()) || 0; var price = parseFloat($currentRow.find('.grpoprice').val()) || 0; // 计算总计并赋值给当前行的总计区域 var total = qty * price; $currentRow.find('.grpototal').text(total); })
额外优化说明
- 加入
parseFloat()和|| 0是为了处理输入为空的情况,避免计算结果出现NaN - 事件绑定到
.partialqty而非整个document,减少不必要的事件监听,提升性能 - 按钮的
removeGRPO也换成了Class,避免重复ID引发其他问题
内容的提问来源于stack exchange,提问作者Raeyim
相关产品推荐
相关产品推荐

