简体   繁体   中英

How to detect "tab keypress" when focus is at a button using JavaScript

I'm just wondering if any of you done an onkeypress on a button.

my button is like this:

asp:Button ID="btnClear" runat="server" Text="Clear" onkeypress="return goToFirst();"/>

the javascript:

function goToFirst(evt) {
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

    alert(charCode);
    if (charCode = 9 ) {
        document.getElementById('txtFirstName').focus();
        document.getElementById('txtFirstName').select();
    }

    return false;

My goal is to detect the tab keypress on a button and set the focus on the specified textbox when tab is pressed.

The problem is that the onkeypress event does not fire when tab key is pressed. other keys like numbers and letters fires the event, but not tab.

Is there a solution to my goal?

Thanks in advance!

use onkeydown . here's a demo

<input ID="btnClear" onkeydown="return goToFirst();"/>

.

function goToFirst(evt) {
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

    alert(charCode);
    if (charCode == 9 ) {
        document.getElementById('txtFirstName').focus();
        document.getElementById('txtFirstName').select();
    }

    return false;
};

我在显示输入后使用 ev.stopPropagation() 和 ev.preventDefault() 解决了类似的问题。

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