views:

17

answers:

2

How can I reliably detect all events that cause the the value of an HTML select to change, while that element still has the focus?

For regular mouse input, either the click or change event works fine. For keyboard input (and for mouse input using the scroll wheel), however, the change event doesn't fire until focus is lost. I get around this by using the keyup event for keyboard changes (and ignoring the mouse wheel problem) but find my code is littered with a lot of stuff like this:

$(".my-select").keyup(handleSelect).change(handleSelect);

function handleSelect() {
    var $this = $(this);

    // don't process keyup events that don't result in change
    if ($this.data('old-val') == $this.val()) { return; }
    $this.data('old-val', $this.val());

    // ... other stuff ...
}

Is there a simpler pattern/recipe that solves this problem (jQuery or straight JavaScript)?

+1  A: 

"change" doesn't fire until the element loses focus, by design. What you're doing may be the only way to solve this. You can also look at selectedIndex as well as value.

Diodeus
A: 

As Diodeus said, the change event is fired when the element loses focus. But you could check if the pressed key is the enter key and then call your function. And I think hardly anybody uses the mouse wheel to change the value of a select box...

elektronikLexikon