如何按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代码,可维护性更强:
对应JS取值改写成<optgroup label="Product Color" data-group-key="color" data-label="product-color">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
相关产品推荐
相关产品推荐

