nikoka nikoka - 16 days ago 5
Javascript Question

Prevent Select2 from toggling selected items when clicking them in the dropdown

When using Select2 (https://select2.github.io/examples.html) for multi-value select boxes you can toggle a selected value from the dropdown. Is there any way to prevent this behaviour? So that you could only remove selected items by clicking on the X next to them.

All help greatly appreciated.

Answer

you can use unselecting event:

$(".js-source-states").select2()
  .on("select2:unselecting", function (e) { 
    // make sure we are on the list and not within input box
    if (e.params.args.originalEvent.currentTarget.nodeName === 'LI') {
      e.preventDefault();
    }
  }
);

plunker: http://plnkr.co/edit/f8w97dSykPmbCZkN65JA?p=preview

see https://select2.github.io/examples.html#programmatic-control for more details,

if you want to close select, use $example.select2("close"); (https://select2.github.io/examples.html#programmatic)

Comments