最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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!

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!

Share Improve this question edited Aug 5, 2010 at 9:02 Gert Grenander 17.1k6 gold badges41 silver badges43 bronze badges asked Aug 5, 2010 at 8:58 PeejayPeejay 981 gold badge1 silver badge4 bronze badges 1
  • 1 You might also want to fix the if statement (; – JSmyth Commented Jul 10, 2013 at 15:18
Add a comment  | 

2 Answers 2

Reset to default 15

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)

  1. 暂无评论