jQuery无法获取动态追加input修改后的值,总价计算失效求助
jQuery动态表单字段取值失败修复方案
问题背景
现有商品表单包含单价、数量、总价三个字段,总价由单价×数量计算得出。页面默认加载的字段计算逻辑正常,点击「添加行」按钮动态追加的字段修改后,无法获取输入值,price.val()返回null导致计算失败。
表单结构示意图:
核心原因
price.val()返回null本质是$('.product-price', parent_tr)没有匹配到对应DOM元素,常见触发原因包括:
- 父行选择器不精准,未匹配到对应商品行
- 动态新增行未正确插入到
.invoice-tableDOM结构中 - 新增行或内部输入框丢失了预设的类名
- 重算元素属性的函数调用顺序错误
修复方案
1. 优化计算逻辑,增加匹配校验
改用更精准的closest方法查找父行,增加元素存在性判断,同时处理空值转换避免计算错误:
$('.invoice-table').on("keyup change", ".product-price, .product-quantity" , function() { // 精准匹配当前输入框所属的商品行 const parent_tr = $(this).closest('tr.product-tr'); if (parent_tr.length === 0) return; const price = parent_tr.find('.product-price'); const quantity = parent_tr.find('.product-quantity'); const total = parent_tr.find('.product-total'); // 校验字段是否存在 if (price.length === 0 || quantity.length === 0) return; // 转为数字处理空值异常 const priceVal = Number(price.val()) || 0; const quantityVal = Number(quantity.val()) || 0; total.val(priceVal * quantityVal); })
2. 调整动态行操作顺序
新增行时严格按照以下顺序执行:
- 克隆/生成新的商品行DOM
- 将新行插入到
.invoice-table的子节点中 - 调用
recalculate_elements()重算元素属性
3. 优化重算属性逻辑
原有逻辑会遍历修改所有已有行的属性,容易导致原有行绑定异常,建议仅给新增行单独设置属性:
// 传入新行DOM和对应序号即可完成属性设置,无需遍历所有行 function setNewRowAttributes(newRow, index) { newRow.attr('data-product', index); newRow.find('.product-key').text(index); newRow.find('.product-id').attr('name', `product[${index}]['id']`); newRow.find('.product-price').attr({ 'name': `product[${index}]['price']`, 'id': `product-price-${index}` }); newRow.find('.product-quantity').attr({ 'name': `product[${index}]['quantity']`, 'id': `product-quantity-${index}` }); newRow.find('.product-total').attr({ 'name': `product[${index}]['total']`, 'id': `product-total-${index}` }); }
4. 校验类名完整性
确保动态生成的商品行带有product-tr类名,行内的单价、数量、总价输入框分别保留product-price、product-quantity、product-total类名,不要在属性修改逻辑中误删类名。
内容的提问来源于stack exchange,提问作者Mohamed Slimane
相关产品推荐
相关产品推荐

