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

动态创建HTML表格行后,jQuery自动填充输入字段失效问题求助

问题原因及解决方案

核心问题

你当前的代码依赖唯一ID定位输入框,但动态生成表格行时,每行的输入框ID都会重复,getElementById只能找到页面中第一个匹配的元素,导致新行的输入框无法被填充。同时没有利用jQuery的事件委托能力处理动态生成的元素。

修复步骤

  1. 移除重复的ID,改用类名标记输入框(类名可重复,适合批量元素)
  2. 使用jQuery的事件委托绑定键盘事件,兼容动态生成的行
  3. 通过当前输入框所在的表格行,定位同行的其他输入框,避免全局查找

修改后的完整代码

HTML结构(含动态行模板)

<table id="dynamicTable">
  <tbody>
    <!-- 初始行 -->
    <tr>
      <td><input type="text" class="form-control text-end scode" name="scode[]" value=""></td>
      <td><input type="text" class="form-control text-end servproname" name="servproname[]"></td>
      <td><input type="text" class="form-control text-end qty" name="qty[]"></td>
    </tr>
    <!-- 动态生成的行将与上述结构完全一致 -->
  </tbody>
</table>

jQuery代码

// 事件委托:绑定到tbody,处理所有动态生成的.scode输入框的keyup事件
$('#dynamicTable tbody').on('keyup', '.scode', function() {
  const $currentRow = $(this).closest('tr'); // 获取当前输入框所在的行
  const inputValue = $(this).val().trim();

  if (!inputValue) {
    // 清空当前行的对应输入框
    $currentRow.find('.servproname').val('');
    $currentRow.find('.qty').val('');
    return;
  }

  // 用jQuery发送AJAX请求,自动处理JSON解析
  $.get(`gfg.php?user_id=${encodeURIComponent(inputValue)}`)
    .done(function(response) {
      // 填充当前行的对应输入框
      $currentRow.find('.servproname').val(response[0]);
      $currentRow.find('.qty').val(response[1]);
    })
    .fail(function() {
      // 请求失败时的兜底处理
      alert('数据获取失败');
      $currentRow.find('.servproname').val('');
      $currentRow.find('.qty').val('');
    });
});

// 数量变化的Calc函数同步改为行内处理
$('#dynamicTable tbody').on('change', '.qty', function() {
  const $currentRow = $(this).closest('tr');
  // 在这里编写你的Calc逻辑,比如获取当前行的其他值进行计算
  // 示例:const qty = $(this).val(); const price = $currentRow.find('.price').val();
});

关键说明

  • 事件委托:$('#dynamicTable tbody').on('keyup', '.scode', ...) 会监听tbody内所有(包括未来动态生成的).scode元素的keyup事件,解决动态元素无法绑定事件的问题
  • 行内定位:$(this).closest('tr') 获取当前输入框所在的行,再用find查找该行内的其他输入框,确保只操作当前行的元素,不会影响其他行
  • 参数编码:encodeURIComponent 避免参数中特殊字符导致的请求错误
  • 错误处理:添加fail回调处理请求失败的情况,提升用户体验

内容的提问来源于stack exchange,提问作者Mian Omer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:33:18