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

如何在Chosen插件中仅显示选中项数量而非全部选中内容

解决Chosen多选时仅显示选中数量的问题

实现思路

Chosen原生没有提供仅显示选中项数量的配置,我们可以通过隐藏默认选中标签 + 在搜索框区域动态更新选中数量的方式实现需求。

具体实现步骤

  1. 添加CSS隐藏默认选中标签
/* 隐藏Chosen默认的选中项标签 */
.chosen-choices .search-choice {
    display: none;
}
/* 确保搜索框占满整个选择器宽度 */
.chosen-choices .search-field {
    width: 100% !important;
}
  1. 编写JS逻辑监听选中事件并更新数量
// 初始化Chosen
$(".chosen-select").chosen();

// 获取目标选择器和Chosen容器
const $select = $(".chosen-select");
const $chosenContainer = $select.next(".chosen-container");
const $searchField = $chosenContainer.find(".chosen-choices .search-field input");

// 定义更新选中数量的函数
function updateSelectedCount() {
    const selectedCount = $select.find("option:selected").length;
    const placeholder = $select.data("placeholder");
    
    if (selectedCount > 0) {
        // 显示选中数量
        $searchField.val(`${selectedCount} 项已选中`);
        // 禁用输入(可选,根据需求调整)
        $searchField.prop("disabled", true);
    } else {
        // 恢复占位符状态
        $searchField.val("");
        $searchField.prop("disabled", false);
        $chosenContainer.find(".chosen-choices").attr("title", placeholder);
    }
}

// 初始化时执行一次
updateSelectedCount();

// 监听Chosen的选中/取消事件
$select.on("change", function() {
    updateSelectedCount();
});

补充说明

  • 若要自定义数量显示文本,直接修改${selectedCount} 项已选中这段内容即可
  • 如需保留搜索功能,移除$searchField.prop("disabled", true)这一行,但此时输入框会同时显示数量和用户输入,需额外处理交互逻辑
  • 确保Chosen初始化代码在DOM加载完成后执行(比如放在$(document).ready()中)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:36:26