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

如何使用原生JavaScript根据选中输入动态显示表单字段

动态显示对应数量的表单输入字段解决方案

核心实现步骤

  • 给需要控制显示的输入字段容器添加唯一标识,方便快速定位
  • 监听下拉选择框的change事件,根据选中值切换字段显示状态
  • 页面初始化时执行一次状态更新,确保默认符合预期行为

修改后的完整代码

HTML部分

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <style>
      body {
        font-family: sans-serif;
      }
    </style>
  </head>

  <body>
    <div id="app"></div>
    <fieldset>
      <div class="form-row field-type">
        <div>
          <label class="required" for="id_type">Select Choices:</label>
          <select name="type" id="id_type">
            <option value="1" selected>1 Choice</option>
            <option value="2">2 Choices</option>
          </select>
        </div>
      </div>

      <div class="choice-field">
        <label for="id_choice_1">Choice 1:</label>
        <input
          type="text"
          name="choice_1"
          class="vTextField"
          maxlength="100"
          id="id_choice_1"
        />
      </div>

      <div class="choice-field" id="choice_2_container">
        <label for="id_choice_2">Choice 2:</label>
        <input
          type="text"
          name="choice_2"
          class="vTextField"
          maxlength="100"
          id="id_choice_2"
        />
      </div>
    </fieldset>

    <script src="src/index.js"></script>
  </body>
</html>

JavaScript部分(src/index.js)

document.getElementById("app").innerHTML = `
<h1>Show fields According to Selected Choice</h1>
<div>
1 field if selected one choice 
2 fields if selected 2 choices
</div>
`;

// 获取元素
const choice2Container = document.getElementById('choice_2_container');
const typeSelect = document.getElementById('id_type');

// 定义状态更新函数
function updateFields() {
  const selectedValue = typeSelect.value;
  choice2Container.style.display = selectedValue === '2' ? 'block' : 'none';
}

// 页面加载时初始化状态
updateFields();

// 监听下拉框变化事件
typeSelect.addEventListener('change', updateFields);

效果说明

  • 页面默认加载时,第二个输入字段隐藏,匹配选中"1 Choice"的预期
  • 切换到"2 Choices"时,第二个字段自动显示;切回"1 Choice"时自动隐藏
  • 无需异步操作,通过同步监听事件即可实现动态更新字段状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:09:33