Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 348
nikoka Avatar asked Jan 06 '23 01:01

nikoka


1 Answers

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)

like image 66
Andriy Avatar answered Jan 13 '23 09:01

Andriy