Hacking the combo box for auto selection with keyboard input.
Published 4.15.2008 by ~mattg
Of the hundreds of input forms in out application, one of them is a simple drop down that, when the user selects an entry, that entry is automatically added to a collection (and subsequently bound to a datagrid). This works by handling the onchange event of the standard HTML select tag.
That event fires every time the item changes. That means if you utilize the keyboard to select an item either by typing the first letter or using the up/down arrow keys, as soon as you change that value, the event fires, and your selection gets added, whether you wanted it or not. Needless to say, keyboard input for that drop down was unusable.
The solution is to selectively allow auto-selection. How did I do this? By adding “flagging” to the onkeydown and onkeyup events of the drop down. Basically, the order of events is as follows:
- onkeydown
- onchange
- onkeyup
So, my onkeydown event checks what key was pressed. If it’s anything other than the enter key, it sets a global javascript variable (true if Enter was pressed, false otherwise). The onchange event then executes based on the value of the global javascript variable (in other words, if it’s true, we add, if it’s false, we don’t). Then, the onkeyup event resets the flag to it’s default state (true).
So, when you change the drop down via the mouse, the onkeydown/onkeyup events don’t fire, so the flag is true, and the item is added. If you navigate via a key press, the flag is false and no auto-selection occurs. If, however, you hit enter, we make sure that the item that is currently selected is added to the collection.
It’s all very hacky and somewhat confusing, but it works. The code itself is trivial, it’s knowing the order of events for the javascript and how to use it that took some effort to figure out.
Filed under .NET Development, Web Development