How to catch keydown event on select2 search field

Select2 4.0.13.
I have tried some way, but event never fire.

$(document).on(‘keydown’, ‘.select2-selection’, function(event) {
// some code;
});

$(document).on(‘keydown’, ‘.select2-search__field’, function(event) {
// some code;
});

Note: keyup event fire good, but I need keydown event, to prevent browser default actions.

Fortunately, I just investigated a similar issue for another poster. You cannot use jQuery to attach a keydown or keypress event handler to capture those events from a Select2; Select2 seems to stopPropagation() on those events. Therefore, you need to install a keydown event handler that captures the event before Select2 handles it. You can do this with document.addEventListener('keydown', handler, true);. That third parameter tells the browser to let your handler handle the keydown event first.

Try that and see if it solves your issue.

1 Like

It works, thanks so much @John30013 !

1 Like

Awesome! I’m glad it worked for you!

1 Like