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

如何实现带全选的分组日期选择功能并展示选中值?

分组工作日/周末列表带全选与选中值展示方案

Hey there! 针对你要实现的分组展示工作日/周末、每组带全选选项、实时展示选中值的需求,这里有个基于你提供的DevExtreme dxList代码的完整实现方案:

核心思路

  1. 给每个分组(工作日/周末)添加「全选」选项,扩展原始数据源
  2. 监听列表的选中事件,处理全选与组内单项的联动逻辑:选中全选时自动勾选组内所有天;组内所有天都选中时自动勾选全选
  3. 实时捕获选中项,格式化后展示出来

完整代码实现

<div id="simpleList"></div>
<div id="selectedValues" style="margin-top: 20px; padding: 10px; border: 1px solid #eee;">
  选中的天数:<span id="selectedDays"></span>
</div>

<script>
var Days = [
  { 
    "key": "Weekdays", 
    "items": [
      {text: "Select All", isAll: true}, // 添加全选标记项
      "Mon", "Tue", "Wed", "Thu", "Fri"
    ] 
  }, 
  { 
    "key": "Weekend", 
    "items": [
      {text: "Select All", isAll: true}, // 添加全选标记项
      "Sat", "Sun"
    ] 
  }
];

$(function () {
  $("#simpleList").dxList({
    dataSource: Days,
    height: "300px",
    grouped: true,
    selectionMode: "multiple", // 开启多选模式
    displayExpr: function(item) {
      return typeof item === 'string' ? item : item.text; // 适配全选项与普通天数的显示逻辑
    },
    onSelectionChanged: function(e) {
      var list = e.component;
      var selectedItems = list.option("selectedItems");
      
      // 遍历每个分组处理全选联动逻辑
      Days.forEach(group => {
        const allItem = group.items.find(item => item.isAll);
        const dayItems = group.items.filter(item => typeof item === 'string');
        
        // 若当前组的全选项被选中,自动勾选组内所有天数
        const isAllSelected = selectedItems.includes(allItem);
        if(isAllSelected) {
          dayItems.forEach(day => {
            if(!selectedItems.includes(day)) list.selectItem(day);
          });
        } else {
          // 若全选项未被选中,检查组内所有天数是否都已选中,是则自动勾选全选
          const allDaysSelected = dayItems.every(day => selectedItems.includes(day));
          if(allDaysSelected) list.selectItem(allItem);
        }
      });
      
      // 整理并展示选中的天数(过滤掉全选项)
      const selectedDays = selectedItems.filter(item => typeof item === 'string');
      $("#selectedDays").text(selectedDays.join(", ") || "无");
    }
  });
});
</script>

关键逻辑说明

  • 数据源扩展:给每个分组的items数组开头添加带isAll: true标记的全选对象,方便后续识别区分
  • 显示适配:通过displayExpr统一处理全选项和普通天数的文本展示,保证界面显示一致
  • 全选联动:在onSelectionChanged事件中,针对每个分组判断全选状态,自动同步组内所有项的选中状态,避免手动操作的不一致
  • 选中值展示:过滤掉全选项后,将选中的天数用逗号分隔展示在页面指定区域,直观呈现选中结果

这样就能完美实现你需要的功能啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:29:11