Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2 - Change configuration dynamically

I'm trying to override the maximumSelectionLength configuration option in select2 dynamically if the user chose the first option, I tried to do it as follows...

$(".some-div select").on("select2:open", function(e) {

    if(e.target.options[0].selected) {
        $(this).select2({
           maximumSelectionLength: 1
        });
    }

});

But it always gives me this error Uncaught TypeError: Cannot read property 'query' of null

How can I do that?

like image 816
Ruby Avatar asked Sep 14 '25 02:09

Ruby


1 Answers

There is a native way to get items index evt.params.data.element.index, So simply do this:

$('#example').select2({
  maximumSelectionLength: 5
});

$("#example").on("select2:select", function(evt) {
  let index = evt.params.data.element.index; // get index 
  if (index === 0) {
    $('#example').select2({ //re-init
      maximumSelectionLength: 1
    });
  }
});

JSFiddle

You can bring back default value of maximumSelectionLength on else

like image 163
Pedram Avatar answered Sep 16 '25 19:09

Pedram