Shotgun
Shotgun

Reputation: 678

Chosen multiple select becomes huge when many/all options are selected

When using Chosen.js on a multiple select field, if there are over 500 options that the user has selected, the list just becomes ridiculously long.

enter image description here

Is there any way I could limit the number of show elements? For example when chosing over 3 options, the user will have (4) options are selected..., instead of them being listed.

enter image description here

I wonder why there's no such option in their documentation.

Thanks in advance.

Upvotes: 4

Views: 1281

Answers (2)

Karan
Karan

Reputation: 23

SOrry I am unable to comment since I don't have enough reputation. But to add to the previous answer, instead of adding a separate container, why don't we just append the n users selected as a <li> item.

Something like this -

$('.element').chosen().change(function() {
    var totalSelected = $(this).find('option:selected').size();
    var placeholder = $(this).find('option:first-child').text();
    if(totalSelected > 3) {
       $(this).next().find('.chosen-choices').find('li.search-choice').hide(),
       $(this).next().find('.chosen-choices')append('<li class="search-choice" <span>'+totalSelected+' users selected. </li>');
}
});

This seems to work for me.

Upvotes: 0

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

You can use something like this:

$('.element').chosen().change(function() {
    var totalSelected = $(this).find('option:selected').size();
    var placeholder = $(this).find('option:first-child').text();
    if(totalSelected > 3) {
        $(this).next().find('.chosen-choices').find('li.search-choice').hide(),
        $(this).next().find('.chosen-choices').find('.literal-multiple').show();
        $(this).next().find('.chosen-choices').find('span.literal-multiple').text(placeholder + " ("+totalSelected+")");
    }
});

The class literal-multiple is a custom element to show the totalSelected elements. You need to add it in the prototype of the chosen plugin:

file chosen.jquery.js

Chosen.prototype.set_up_html = function() {
   //stuff
   if(this.is_multiple) {
     var selVal  = this.default_text;
     this.container.html('<ul class="chosen-choices"><span class="literal-multiple"></span></ul>');
   }
};

Upvotes: 1

Related Questions