I don’t think what you want to do is possible with Select2. Select2 tries to replicate (and add to) the functionality of a standard HTML <select>
control. Since standard HTML <select>
controls don’t work this way, it’s not surprising that Select2 doesn’t work this way either.
Note: I tried attaching a keypress event handler to the <body>
to capture the Enter key and determine if it was triggered on one of the <li>
elements in the Select2. But Select2 seems to swallow (i.e., preventPropagation()
) those events and not allow them to bubble up the DOM. However, if you use plain JavaScript document.addEventListener('keydown', handler, true)
, that third parameter tells the browser to run this event handler before any others. In that case you can inspect the event’s srcElement
or target
properties (they seem to point to the same element) to see which element the event was triggered on. (In my investigation, the keydown event is triggered on the input.select2-search__field
element.) Your handler code can then determine whether (a) the Enter key was pressed, and (b) whether there is a current selection—and if so, programmatically clear the current selection.
Good luck!