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

复制含文本输入框与下拉菜单的div:解决选中状态丢失及空字段需求

解决表单元素克隆的两个问题:保留选中状态/生成空字段

一、克隆时保留下拉菜单的选中状态

cloneNode(true)只会复制DOM的静态结构,不会同步表单元素的动态交互状态(比如select的选中项、input的输入值),需要手动同步状态:

  • 克隆节点后,获取原节点select的selectedIndex,赋值给克隆节点的select
  • 若需要同步input的内容,同样将原input的value赋值给克隆的input
  • 移除克隆节点的id,避免页面出现重复id

修改后的代码:

<script>
function myFunction() {
  const node = document.getElementById("category_div");
  const clone = node.cloneNode(true);
  
  // 移除克隆节点的id,避免重复
  clone.removeAttribute('id');
  
  // 同步原select的选中状态
  const originalSelect = node.querySelector('select');
  const clonedSelect = clone.querySelector('select');
  clonedSelect.selectedIndex = originalSelect.selectedIndex;
  
  // 同步原input的输入内容(按需选择)
  const originalInput = node.querySelector('input');
  const clonedInput = clone.querySelector('input');
  clonedInput.value = originalInput.value;
  
  document.body.appendChild(clone);
}
</script>

<div class="category_div" id="category_div"> 
    Project number:
    <select>
    <option value=""> Select </option>
    <option value="1"> 1 </option>
    <option value="2"> 2 </option>
    </select>

    field#2
    <input type="text" placeholder="this will be an example..." name="uname" required>
    
</div>

<p> 
<button onclick="myFunction()" class="button btn-duplicate"> + </button>
</p>

二、克隆时生成空的输入字段

如果需要克隆出的div中select和input都处于空白状态,只需在克隆后重置元素状态:

  • 将克隆的select的selectedIndex设为0(对应默认空选项)
  • 将克隆的input的value设为空字符串
  • 同样移除克隆节点的id

修改后的代码:

<script>
function myFunction() {
  const node = document.getElementById("category_div");
  const clone = node.cloneNode(true);
  
  // 移除克隆节点的id,避免重复
  clone.removeAttribute('id');
  
  // 重置select为默认空选项
  const clonedSelect = clone.querySelector('select');
  clonedSelect.selectedIndex = 0;
  
  // 清空input内容
  const clonedInput = clone.querySelector('input');
  clonedInput.value = '';
  
  document.body.appendChild(clone);
}
</script>

<div class="category_div" id="category_div"> 
    Project number:
    <select>
    <option value=""> Select </option>
    <option value="1"> 1 </option>
    <option value="2"> 2 </option>
    </select>

    field#2
    <input type="text" placeholder="this will be an example..." name="uname" required>
    
</div>

<p> 
<button onclick="myFunction()" class="button btn-duplicate"> + </button>
</p>

额外提示

如果需要提交表单,建议给克隆出来的表单元素设置带唯一标识的name属性(比如uname_1、uname_2),避免提交时参数被覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:57:35