简体   繁体   English

Select2下拉菜单在第三个所选项目上显示“ x selected”

[英]Select2 dropdown to show “x selected” on third selected item

The following code uses select2 to allo multiple selection from a dropdown. 以下代码使用select2从一个下拉列表中分配多个选择。 My question is how can I show a "x selected" after third choice, instead of all the choices and have a huge textbox? 我的问题是,如何在第三个选择之后显示“ 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();

I have a jSfiddle here 我在这里有一个jSfiddle

http://jsfiddle.net/ishanbakshi/fyhsz9ra/ http://jsfiddle.net/ishanbakshi/fyhsz9ra/

I have worked hard and managed to supply a jQuery solution for you. 我努力工作并设法为您提供了jQuery解决方案。 Change your JavaScript to this: 将您的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();
}
}


})

I've checked it in the jsFiddle and it works perfectly. 我已经在jsFiddle中对其进行了检查,并且效果很好。 It's not possible to make a more elegant solution. 不可能做出更优雅的解决方案。 If you really want a more elegant one, you need either to develop your own control or change the source code of Select2. 如果您确实想要一个更优雅的控件,则需要开发自己的控件或更改Select2的源代码。

I have created a fiddle . 我制造了一个小提琴 Try this way.. 尝试这种方式..

$("#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM