开发者

javascript onchange vs onkeyup events for <Select> menu (Up and Down keys don't fire onchange event in Firefox)

I have a <select id="myselect" name="myselect" onCha开发者_Python百科nge="(myfunction();)">...</select> which works perfect in IE and Opera. The word "perfect" means the event fired when you change the values from the drop-list by mouse or by any of "Up", "Down", "PageUp"(not for Opera), "PageDown"(not for Opera), "Home" and "End" keys when select menu is active (blue). The problem appears when you test it using Firefox, 3.6.Xv. Nothing happens when you use "Up" and "Down", but for mouse it still works. Do you recommend to use onkeyup event? I've tried it, it "catches" up and down, but, IE appears to have both onChange and onkeyup event. But I need just one event. How do people solve this issue?

Thank you.


I recommend that you keep using the change event. The Firefox implementation makes lots of sense for keyboard users. If you tab to the select element and choose an entry using Up and Down keys (and you have to press them a lot for a lengthy list) you don't want to trigger tons of actions on the web page. It is ok to have the action executed once you've selected the correct entry and moved on to something else.


This is a pretty dirty hack, but you can force the the change event to fire by doing this:

element.addEventListener('keyup', function(evt){
    evt.target.blur();
    evt.target.focus();
}, false);

So you'd register an event listener for change as well, and that function would get called when the user presses a key on the <select> via the code above.

You may want to scope this only to Firefox, but AFAIK you'd have to use UA sniffing for that so it's up to you if that's acceptable.

Source


You could be clever and make your own handler for the keyup event which tests the keycode to see if it was an up arrow or down arrow, and fires the change event accordingly.

My own js isn't good enough to write you an example but I could show some example jQuery to do that:

$('yourSelect').keyup(function(e)
{

    if (e.keyCode===38)
    {
        //this is an up arrow press

        //trigger the change event
        $('yourSelect').change();
    }
    else if (e.keyCode===40)
    {
        //down arrow has pressed

        //trigger the change event
        $('yourSelect').change();
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜