Marc Wilson
Marc Wilson

Reputation: 140

Chosen.js - is it possible to limit the number of items selected?

I have a client that wants to give users the option to select up to 5 additional options from a list. I like the Chosen.js concept, but how can I limit the selection? I suppose one solution is to use the onChange to count the number selected and then disable the remainder, but is there a neater solution?

Upvotes: 5

Views: 4544

Answers (2)

user2609739
user2609739

Reputation: 1

max_selected_options: 5 is not working in my case. So I fixed as follows.

var countSelect = 0;
$(".chosen-select").chosen().change( function (e, params) {         
    if(params.deselected != undefined) { countSelect--; } 
    if(params.selected != undefined) { countSelect++; } 
    if(countSelect > 3) {           
        $('.chosen-select option[value="'+params.selected+'"]').attr('selected', false);
        $(this).trigger('chosen:updated');
        countSelect--;
    } 
});

Try it. Its working very smooth.

Upvotes: 0

mccannf
mccannf

Reputation: 16659

Chosen provides a max_selected_options to allow you to do this:

$(".chzn-select").chosen({ max_selected_options: 5 });

Upvotes: 12

Related Questions