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.

2 Likes

It works, thanks so much @John30013 !

1 Like

Awesome! I’m glad it worked for you!

1 Like

document.addEventListener(‘keydown’, handler, true);

What I will write in handler ??

can write an example plees

I also have the same problem. I need your help pro.
" keyup event fire good, but I need keydown event, to prevent browser default actions"

You should use document.addEventListener('keydown', handler, true); instead of using jQuery.

Example:

function myhandler(event){
if (event.keyCode == 117) { // F6

        event.preventDefault();

        event.stopPropagation();

// do what you want when user press F6 on keyboard;

        return false;

    }
}

document.addEventListener('keydown', myhandler, true);

See example code above.

Saturn_Node See example code above.

Can you give me your phone number on WhatsApp?

Thanks for your kind pro.