Unselect on enter press (in dynamic dropdown)

(I am aware CTRL+Spacebar will unselect)

Select2 has a dynamic dropdown consisting of a ‘UL’ with ‘LI’ and when you press enter on a unselected item it becomes selected.

I would like to make the opposite be true, if it is selected and enter is pressed then unselect it.

So far everything I have tried has failed and I think it is because the is destroyed too soon?

I have tried

 1. making a jquery loop on the 'UL' and putting events on each 'LI'
 2. jquery keypress even targeting $('#UL_Id li').on('keypress' doit ...
 3. manually adding onkeypress="doItFucntion()" attribu

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!