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

如何在Tom-select中选中全部选项或单个选项组?

实现TomSelect全选及整组选中功能

1. 添加全选按钮

在TomSelect组件旁新增全选按钮,用于触发全选操作:

<div>
  <button id="select-all">全选</button>
  <select id="my-select" multiple>
    <optgroup label="分组1">
      <option value="1">选项1</option>
      <option value="2">选项2</option>
    </optgroup>
    <optgroup label="分组2">
      <option value="3">选项3</option>
      <option value="4">选项4</option>
    </optgroup>
  </select>
</div>

2. 编写全选逻辑

初始化TomSelect后,给全选按钮绑定点击事件,一次性选中所有选项:

const tomSelect = new TomSelect('#my-select', {
  plugins: ['remove_button'],
  maxItems: null, // 开启无限制多选
  multiple: true
});

// 全选按钮点击事件
document.getElementById('select-all').addEventListener('click', () => {
  const allOptionValues = Array.from(tomSelect.options).map(opt => opt.value);
  tomSelect.setValue(allOptionValues);
});

3. 实现整组选中

给每个分组标题添加点击事件,点击时选中/取消该组下所有选项:

tomSelect.on('initialize', () => {
  // 获取所有分组标题元素
  const groupHeaders = document.querySelectorAll('.ts-dropdown .optgroup-header');
  
  groupHeaders.forEach(header => {
    header.style.cursor = 'pointer';
    header.addEventListener('click', (e) => {
      // 获取当前分组下的所有选项
      const groupOptions = e.target.nextElementSibling.querySelectorAll('.option');
      const groupValues = Array.from(groupOptions).map(opt => opt.getAttribute('data-value'));
      
      // 判断当前组是否已全选,切换选中状态
      const isAllSelected = groupValues.every(val => tomSelect.isSelected(val));
      if (isAllSelected) {
        tomSelect.removeItems(groupValues);
      } else {
        tomSelect.addItems(groupValues);
      }
    });
  });
});

补充说明

  • 必须确保TomSelect初始化时开启multiple: true和maxItems: null,否则无法支持多选操作。
  • 代码中使用的.optgroup-header、.option是TomSelect默认生成的类名,若自定义了组件样式,需对应调整选择器。
  • 若不需要切换选中状态,可直接移除判断逻辑,只保留选中操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:55:56