Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .change() event doesn't fire on select list from keyboard: how can I override this?

Tags:

jquery

The jQuery .change() event doesn't fire the second time the user types and presses Enter to select an item. It does fire the first time.

See: http://jsfiddle.net/CtXbU/

If you focus on the list and type AD and press Enter, [EDIT] the alert fires. But if you then type AG and press Enter, nothing happens. The alert only pops up when you click away from the list.

What do I do if I want to handle the user changing the list both with the mouse and the keyboard?

I know I can use .keypress() to handle keyboard events, but it feels odd to have two separate sections of code both doing the same thing.

Is there a single jQuery event that would handle both mouse and keyboard changes as soon as they occur?

Thanks!

** UPDATE **

This might clarify my question: http://jsfiddle.net/Bybr2/2/

// How can I create an event (or handler) that 
// (a) fires AS SOON AS keypress is invoked from user keyboard input
// (b) also fires AS SOON AS change is invoked from user mouse input
// (c) does not fire a second time when change is invoked after keypress, when the user clicks away following keypress?

change after keypress can be very confusing - it only occurs when the user presses Enter or clicks away, so if I'm making client-side changes then, the user may well be very surprised!

The only solution I can think of is some kind of variable like user_has_just_done_keypress which is set as true on keypress and then reset to false on the next change event, but it feels very messy. It also wouldn't work if you had a change from the mouse before the change from the user refocussing. Argh!

like image 579
AP257 Avatar asked Feb 26 '23 01:02

AP257


1 Answers

Add handler for keyup event, not keypress! If you use the same handler for keypress as for change, it does not work well in Firefox for example.

$("select").bind('change keyup', select_handler);

and handler

function select_handler() {
    $(this).val();
};
like image 152
Nick Avatar answered May 20 '23 05:05

Nick