简体   繁体   中英

Javascript Keydown event works perfect in Fireforx, Chrome but only once in Internet Explorer

I am developing a small questionnaire and fire an ASP LinkButton click when the TAB key is pressed from Javascript.

The Javascript is as follows:

 document.onkeydown = keydown;
    function keydown(event) {
        if (event.key == "Tab" || event.keyCode == 9 || event.which == 9 && !event.shiftKey)
            __doPostBack('<%=btnNext.UniqueID%>', '', true, '', '', false, true); 
        else if (!event) {
            if (window.event.keyCode == 9 && window.event.keyCode == 9 && !window.event.shiftKey)
                __doPostBack('<%=btnNext.UniqueID%>', '', true, '', '', false, true);
        }
    }


My ASP LinkButton looks like this:

 <asp:LinkButton ID="btnNext" runat="server" CausesValidation="true"></asp:LinkButton>


The LinkButton causes the page to reload with the next question. It all works perfectly in Firefox and Chrome, but not in IE.

In IE only the first TAB key press works, but when I then press TAB again the second time, after the next question was loaded, nothing happens.

Any idea how to make it work in IE? Hate these browser differences....

You need to return false to cancel the default action caused by tabbing

document.onkeydown = keydown;
function keydown(event) {
    if(!event){
        event = window.event;
    }
    if (event.key == "Tab" || event.keyCode == 9 || event.which == 9 && !event.shiftKey){
        __doPostBack('<%=btnNext.UniqueID%>', '', true, '', '', false, true); 
        // Only capture tab events
        return false;
    }
    return true;
}

(I have also DRY'ed you code out a bit)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM