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

求助:无法获取多个select元素选中值并添加至对象数组

问题分析

你当前代码存在两个核心问题:

  • 用单个全局变量selectedVal存储两个下拉框的选中值,无论哪个下拉框修改,都会覆盖该变量,导致最终favColor和location只能拿到最后一次修改的下拉框值。
  • changes函数里每次下拉框变化都会往list推入仅含selectedVal的无效对象,污染了目标数组。
修复方案

直接在表单提交时获取每个下拉框的当前选中值,无需额外全局变量和change事件监听,代码更简洁可靠:

let list = [];

const addDets = (ev) => {
  ev.preventDefault();
  // 直接获取各表单元素的当前值
  let officials = {
    name: document.getElementById("name").value,
    age: document.getElementById("age").value,
    favColor: document.getElementById("fav").value,
    location: document.getElementById("loc").value
  };
  // 可选:验证下拉框是否已选择
  if (!officials.favColor || !officials.location) {
    alert("请选择完整信息");
    return;
  }
  list.push(officials);
  document.forms[0].reset();
  console.log(list);
};

document.addEventListener("DOMContentLoaded", () => {
  document.getElementById('btn').addEventListener('click', addDets);
});

对应的HTML无需修改:

<body>
  <form action="" id="form">

    <label for="name">Name:</label>
    <input type="text" name="name" id="name">

    <label for="age">Age:</label>
    <input type="number" name="age" id="age">

    <select name="favorites" id="fav">
      <option value="" selected disabled>Favorite Colors</option>
      <option value="Red">R</option>
      <option value="Blue">B</option>
      <option value="Yellow">Y</option>
    </select>

    <select name="location" id="loc">
      <option value="" selected disabled>Location</option>
      <option value="L">L</option>
      <option value="V">V</option>
      <option value="M">M</option>
    </select>

    <button id="btn" type="submit">OK</button>

  </form>
</body>
</html>
可选方案(实时监听下拉框)

如果确实需要实时监听下拉框变化并存储值,可使用两个独立变量分别存储,避免覆盖:

let list = [];
let selectedFavColor = "";
let selectedLocation = "";

function changes(event) {
  // 根据下拉框ID区分存储目标
  if (event.target.id === "fav") {
    selectedFavColor = event.target.value;
  } else if (event.target.id === "loc") {
    selectedLocation = event.target.value;
  }
}

const selectEls = document.querySelectorAll("select");
selectEls.forEach((select) => {
  select.addEventListener('change', changes);
});

const addDets = (ev) => {
  ev.preventDefault();
  let officials = {
    name: document.getElementById("name").value,
    age: document.getElementById("age").value,
    favColor: selectedFavColor,
    location: selectedLocation
  };
  if (!officials.favColor || !officials.location) {
    alert("请选择完整信息");
    return;
  }
  list.push(officials);
  document.forms[0].reset();
  // 重置选中值
  selectedFavColor = "";
  selectedLocation = "";
  console.log(list);
};

document.addEventListener("DOMContentLoaded", () => {
  document.getElementById('btn').addEventListener('click', addDets);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:32:45