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

在<select multiple>标签中如何将选中<option>的值存入数组并拼接为字符串

解决方案

1. 获取选中值数组

多选场景下可以直接使用 <select> 元素内置的 selectedOptions 属性获取所有选中项,转换为数组后遍历提取value即可:

const selectElement = document.getElementById('test');
const optionArray = Array.from(selectElement.selectedOptions).map(item => item.value);

如果需要兼容非常老的浏览器,也可以遍历所有option判断选中状态实现同样效果:

const selectElement = document.getElementById('test');
const optionArray = [];
for (let option of selectElement.options) {
  if (option.selected) {
    optionArray.push(option.value);
  }
}

2. 拼接目标字符串

直接使用数组的join方法即可实现自动拼接,不需要手动遍历数组元素:

const resultStr = 'You select ' + optionArray.join(' and ');

当选中A和C时,上述代码得到的resultStr值为 You select A and C,选中多个元素时也会自动按规则拼接所有值。

完整可运行示例

<select multiple id="test">
  <option value="A">Option A</option>
  <option value="B">Option B</option>
  <option value="C">Option C</option>
  <option value="D">Option D</option>
</select>

<script>
const testSelect = document.getElementById('test');
// 绑定值变化事件,选中项变更时自动更新结果
testSelect.addEventListener('change', function() {
  const selectedValues = Array.from(this.selectedOptions).map(opt => opt.value);
  const showStr = 'You select ' + selectedValues.join(' and ');
  // 测试输出,可根据需求替换为其他业务逻辑
  console.log(showStr);
})
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 23:54:07