简体   繁体   中英

Select2 dropdown to show “x selected” on third selected item

The following code uses select2 to allo multiple selection from a dropdown. My question is how can I show a "x selected" after third choice, instead of all the choices and have a huge textbox?

<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

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

I have worked hard and managed to supply a jQuery solution for you. Change your JavaScript to this:

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

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('');
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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