[英]Select2 dropdown to show “x selected” on third selected item
以下代码使用select2从一个下拉列表中分配多个选择。 我的问题是,如何在第三个选择之后显示“ x selected”,而不是所有选择并显示一个巨大的文本框?
<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
$("#e1").select2();
我在这里有一个jSfiddle
我努力工作并设法为您提供了jQuery解决方案。 将您的JavaScript更改为此:
$("#e1").select2();
$(document).ready(function(){
var showHugeSelect = false;
$("#s2id_e1 ul.select2-choices").prepend("<button id='btnE1ShowAll' style='display: none;' />")
$("#btnE1ShowAll").click(function(e){
$("#s2id_e1 .select2-search-choice").show();
$("#btnE1ShowAll").hide();
showHugeSelect = true;
function hideHugeSelect(){
showHugeSelect = false;
}
setTimeout(hideHugeSelect, 5000);
})
setInterval(customizeSelectE1, 500);
function customizeSelectE1(){
var selectedCount = $("#s2id_e1 .select2-search-choice").length;
if(selectedCount > 2 && !showHugeSelect){
$("#s2id_e1 .select2-search-choice").hide();
$("#btnE1ShowAll").html(selectedCount + " selected").show();
}
}
})
我已经在jsFiddle中对其进行了检查,并且效果很好。 不可能做出更优雅的解决方案。 如果您确实想要一个更优雅的控件,则需要开发自己的控件或更改Select2的源代码。
我制造了一个小提琴 。 尝试这种方式..
$("#e1").select2().on('change', function() {
if ($(this).val().length >= 3) {
var html = $('.select2-choices li:first-child').clone();
$('.select2-choices li:not(:last-child)').remove();
var divContent = html.find('div').html($(this).val().length + ' Selected');
$('.select2-choices').prepend(html).find('a').on('click', function() {
$(this).parent('li').remove();
$("#e1").val('');
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.