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

如何按optgroup分组获取select多选框中已选中的option值

实现方案

原生JavaScript实现(无第三方依赖)

function getGroupedSelectValues(selectId) {
  const select = document.getElementById(selectId);
  // 用reduce聚合选中项,直接生成目标结构
  return Array.from(select.selectedOptions).reduce((groupResult, option) => {
    // 可根据实际需求调整分组key的取值规则,示例对齐你期望的输出格式
    const optGroup = option.parentElement;
    const groupKey = optGroup.dataset.label === 'product-color' ? 'color' : optGroup.dataset.label;
    // 分组不存在则初始化
    groupResult[groupKey] ||= [];
    groupResult[groupKey].push(option.value);
    return groupResult;
  }, {});
}

// 调用示例
const selectedResult = getGroupedSelectValues('xpto');
console.log(selectedResult);

逻辑说明

  • 直接调用浏览器原生selectedOptions属性获取所有选中项,无需手动遍历全部option判断选中状态,性能更高
  • 分组key的取值逻辑可灵活调整:如果要直接用optgroup的显示label作为key,直接取optGroup.label即可;如果可以修改DOM结构,建议给optgroup新增自定义属性存储分组key,比如data-group-key="color",后续新增分组无需修改JS代码,可维护性更强:
    <optgroup label="Product Color" data-group-key="color" data-label="product-color">
    
    对应JS取值改写成const groupKey = optGroup.dataset.groupKey即可。

jQuery实现(适用已引入jQuery的项目)

const selectedResult = {};
$('#xpto option:selected').each(function() {
  const $opt = $(this);
  const groupKey = $opt.parent().data('label') === 'product-color' ? 'color' : $opt.parent().data('label');
  selectedResult[groupKey] ||= [];
  selectedResult[groupKey].push($opt.val());
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:24:01