Select2 jQuery插件显示结果中所选项目的数量,而不是标签 [英] Select2 jquery plugin show number of selected items in the result instead of tags
问题描述
我正在使用 Select2 jQuery插件.
当我使用多重下拉菜单选项时.所选项目的结果在框中显示为标签,但我只想显示所选项目的数量.
When I am using the multiple dropdown option. The result of selected items is shown as tags in a box but, I just want to show the number of items selected.
使用 Select2 jQuery插件
HTML
<select multiple style="width:100%">
<option value="1">Name1</option>
<option value="2">Name2</option>
<option value="3">Name3</option>
<option value="4">Name4</option>
<option value="5">Name5</option>
<option value="6">Name6</option>
<option value="7">Name7</option>
</select>
JS
$('select').select2();
我想要输出如下
而不是类似输出的标签.
instead of tag like output.
Example working Fiddle
推荐答案
您可以在初始化select2之后添加此代码
You can add this code after initializing select2
$('select').on('select2:close', function (evt) {
var uldiv = $(this).siblings('span.select2').find('ul')
var count = $(this).select2('data').length
if(count==0){
uldiv.html("")
}
else{
uldiv.html("<li>"+count+" items selected</li>")
}
Ref: jsfiddle
Reference to select2 events: Here
如果要在用户取消选择所有内容时显示空白,
请使用以下小提琴:此处
If you want to display a blank when user deselects everything,
Use this fiddle: here
已更新,以消除数据取消选择方面的缺陷并将其更改为主要答案.
小提琴:此处
Updated to remove flaw in deselection of data and changed it to main answer.
Fiddle: here
这篇关于Select2 jQuery插件显示结果中所选项目的数量,而不是标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!