Search code examples
javascriptjqueryjquery-select2-4jquery-select2

How can I set maximumSelectionLength while closeOnSelect is false in Select2?


I have the following code:

$("#select2").select2({ closeOnSelect: false,
                        maximumSelectionLength: 5,
                        ...  // I have AJAX implemented here
                      });

When I have closeOnSelect to be false and have the maximumSelectionLength set, I'm able to select more than 5 items without any problem. When I click away from the dropdown while having more than 5 items selected and I try to add another, I get the message "You can only select 5 items".

Is there any workarounds to have these two properties work together without clashing?

I'm currently using Select2 4.0.1.


Update:

I took pratikwebdev's advise and added the following code:

$("#select2").select2({ closeOnSelect: false,
                        maximumSelectionLength: 5,
                        ...  // I have AJAX implemented here
}).on("change", function(e) {
    if(e.target.length == 5) {
        $("#select2").select2({closeOnSelect: true,
                               maximumSelectionLength: 5,
        });
    }
});

This actually will close the dropdown once I select 5 items and the maximumSelectionLength property will work properly. But now the closeOnSelect is true so each time I select something, the dropdown will close.

Is there a way to toggle closeOnSelect?


Solution

  • This should work fine.

      $("#select2").change(function(){
          var ele = $(this);
          if(ele.val().length==5)
          {
            ele.select2('close');
          }
      });