开发者

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

开发者 https://www.devze.com 2023-01-10 02:55 出处:网络
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();\"/>

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(ch开发者_运维知识库arCode);
    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;
};


I solved a similar problem using ev.stopPropagation() and ev.preventDefault() after show the input.

0

精彩评论

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