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

如何获取Bootstrap Multiselect中选中的optgroups数组?

如何获取Bootstrap Multiselect中选中的optgroups数组?

当你开启了enableClickableOptGroups选项后,要获取被选中的optgroups数组,可以通过以下两种方式实现:

方法一:通过插件实例获取

先获取插件实例,再从原生select元素中筛选出被标记为选中的optgroup:

// 获取插件实例
const multiselect = $('#your-select-id').data('multiselect');

// 筛选出被选中的optgroup(带有active类)
const selectedOptgroups = multiselect.$select.find('optgroup.active');

// 转换为包含label和value的数组
const selectedOptgroupArray = selectedOptgroups.map(function() {
  return {
    label: $(this).attr('label'),
    value: $(this).attr('value') // 若optgroup未设置value可省略
  };
}).get();

方法二:直接操作下拉菜单DOM

下拉菜单中被选中的optgroup会带有multiselect-group active类,可直接筛选:

// 选中下拉菜单中处于激活状态的optgroup
const selectedOptgroupNodes = $('.multiselect-container .multiselect-group.active');

// 提取信息转为数组
const selectedOptgroupArray = selectedOptgroupNodes.map(function() {
  const label = $(this).text().trim();
  // 关联到原生select中的对应optgroup
  const originalOptgroup = $('#your-select-id').find(`optgroup[label="${label}"]`);
  
  return {
    label: label,
    value: originalOptgroup.attr('value')
  };
}).get();

注意事项

  • 只有当用户直接点击optgroup进行选择时,optgroup才会被添加active类;如果是手动选中optgroup下所有子option,optgroup不会被标记为选中,这种情况上述方法不会将其纳入结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:32:16