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

如何获取name为skills[]的select标签中所有选中选项的值?

解决获取含方括号name属性的select选中值问题

我来帮你梳理下这个问题的解决过程,以及之前尝试踩过的坑:

问题场景

你有如下的HTML结构,需要提取所有name="skills[]"的select标签中选中选项的值,预期结果是 ['one', 'two', 'three']:

<div id="container">
  <div> <button>Add item</button> </div>
  <div class="well">
    <button>Delete</button>
    <div>
      <label>Skill</label>
      <select name="skills[]">
        <option value="one" selected="">one</option>
        <option value="two">two</option>
        <option value="three">three</option>
      </select>
    </div>
    <!-- 其他表单元素 -->
  </div>
  <!-- 更多.well容器 -->
</div>

为什么前两次尝试失败?

  1. 第一次选择器语法错误
    你用了document.querySelector('#container').querySelectorAll('select[name=skills[]]'),但CSS选择器里的方括号是特殊字符(用于属性选择器),直接写skills[]会让解析器混淆语法,必须用引号把属性值包裹起来,比如select[name="skills[]"]才是合法的选择器。

  2. 第二次选择器匹配不到元素
    document.querySelector('#container').querySelectorAll('.well > select:first-child')返回空NodeList,是因为HTML结构里.well的直接子元素是<button>,而select嵌套在内部的<div>里,>表示匹配直接子元素,所以这个选择器根本找不到目标select。

正确解决方案

直接使用属性选择器配合:checked伪类,一步到位获取所有选中的选项,再提取它们的value:

Array.from(document.querySelectorAll('[name="skills[]"] option:checked')).map(option => option.value)

这段代码的逻辑:

  • [name="skills[]"]精准匹配所有name属性为skills[]的元素(用引号包裹属性值避免语法错误)
  • option:checked筛选出每个select里被选中的选项
  • Array.from把返回的NodeList转换为数组,再通过map遍历提取每个选项的value,最终得到你想要的['one', 'two', 'three']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:07:54