开发者

How to detect all change/click events of HTML select that still has focus?

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 handleS开发者_开发技巧elect() {
    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)?


"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.


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜