Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 349
Peejay Avatar asked Aug 05 '10 08:08

Peejay


People also ask

How to detect tab key is pressed in JavaScript?

function checkTabPress(key_val) { if (event. keyCode == 9) { // Here read the active selected link. } }

How to call tab key in JavaScript?

Q: How to call a function when pressing the tab key in JavaScript? Answer: Add an event listener to the document and match the keycode with the tab keycode. If the condition is true then call function. Do comment if you have any doubts or suggestions on this JS event topic.


1 Answers

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;
};
like image 90
Reigel Avatar answered Sep 28 '22 17:09

Reigel