Thursday, November 3, 2011

How to detect tab key is pressed by user in javascript

In many times we need to check or detect Tab key from cross browser javascript method to implement some business logic. In this regard here i want to show you how one can detect that user pressed or enter Tab key. One can also detect the TAB key to cancel the action. So you can do lots of work based on checking TAB key depends on user or client requirement.

Keep in mind one thing that TAB Key only fires on onkeydown and the onkeyup event.No onkeypress event is fired.


The below cross-browser javascript method will check or detect tab key pressed and popup an alert message.
1function DetectTab(e)
2    {
3    var KeyCode = (e.which) ? e.which : e.keyCode
4    if(KeyCode==9)
5        {
6            alert("You have pressed Tab Key.");
7        }
8    }

For complete example check or read the below HTML Markup code:
01<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Detect_Tab_Key.aspx.cs" Inherits="Detect_Tab_Key" %>
02 
03<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04 
05<html xmlns="http://www.w3.org/1999/xhtml" >
06<head runat="server">
07    <title>Check detect user entered Tab Key</title>
08    <script type="text/javascript">
09    function DetectTab(e)
10    {
11    var KeyCode = (e.which) ? e.which : e.keyCode
12    if(KeyCode==9)
13        {
14            alert("You have pressed Tab Key.");
15        }
16    }
17</script>
18</head>
19<body>
20    <form id="form1" runat="server">
21    <div>
22    <asp:TextBox runat="server" ID="txt" onkeydown="DetectTab(event)"></asp:TextBox>
23    </div>
24    </form>
25</body>
26</html>

Please also note that 9 is the key code of TAB key.

No comments:

Post a Comment