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

jQuery克隆表格行时Dropdown Select未同步,需保留选中值

解决表格行克隆时同步下拉框选中值的问题

原代码克隆行时未保留下拉框的选中状态,可通过以下方式修改:

修正后的JavaScript代码

$("input.tr_clone_add").live('click', function() {
  var $tr = $(this).closest('.tr_clone');
  var $clone = $tr.clone();
  
  // 同步原行下拉框的选中值到克隆行
  var animalVal = $tr.find('select[name="animal"]').val();
  var vehicleVal = $tr.find('select[name="vehicle"]').val();
  $clone.find('select[name="animal"]').val(animalVal);
  $clone.find('select[name="vehicle"]').val(vehicleVal);
  
  // 清空克隆行的备注输入框(按需调整)
  $clone.find('input[name="remarks"]').val('');
  
  $tr.after($clone);
});

关键修改点

  • 移除了无效的选择器代码(原代码中.form-control js-example-basic-single在HTML中不存在,无实际作用)
  • 手动获取原行两个下拉框的选中值,赋值给克隆行对应的下拉框
  • 保留了清空备注输入框的逻辑(可根据需求删除或修改)

完整可运行代码示例

<table>
  <tr class="tr_clone">
    <td>
      <input type="button" name="add" value="clone row" class="tr_clone_add" /><br><br>
      <select name="animal" id="number">
        <option value="cow">cow</option>
        <option value="horse">horse</option>
        <option value="dog">dog</option>
        <option value="cat">cat</option>
      </select>
      &nbsp;
      <select name="vehicle" id="letter">
        <option value="car">car</option>
        <option value="ship">ship</option>
        <option value="plane">plane</option>
      </select>
      &nbsp;
      <input name="remarks" type="text">
      <br>
      <hr>
    </td>
  </tr>
</table>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

<script>
$("input.tr_clone_add").live('click', function() {
  var $tr = $(this).closest('.tr_clone');
  var $clone = $tr.clone();
  
  var animalVal = $tr.find('select[name="animal"]').val();
  var vehicleVal = $tr.find('select[name="vehicle"]').val();
  $clone.find('select[name="animal"]').val(animalVal);
  $clone.find('select[name="vehicle"]').val(vehicleVal);
  
  $clone.find('input[name="remarks"]').val('');
  
  $tr.after($clone);
});
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:20:41