You have the right idea, but you’re targeting the wrong HTML element. The selector for the text entry box in the Select2 widget is input.select2-search__field
. And you should use the input
event rather than keydown
, because input
only fires when the content of the textbox changes, whereas keydown
fires on every keystroke (including cursor movement keys, which by themselves don’t change the textbox’s value).
One “wrinkle” is that Select2 doesn’t actually create the input
element until the first time the Select2 is opened. So to force it to create the input
element (so you can attach the event handler) you need to open it programmatically, attach your handler, then close it programmatically. Here’s an example of how to do that: http://jsfiddle.net/jpisello/vkrxu6do/33/. Look at the Javascript code starting at line 46.