Sunday, March 7, 2010

How to detect tab key is pressed by user in javascript




Please visit my new Web Site WWW.Codedisplay.com



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.
function DetectTab(e) 
    {
    var KeyCode = (e.which) ? e.which : e.keyCode
    if(KeyCode==9)
        {
            alert("You have pressed Tab Key.");
        }
    }

For complete example check or read the below HTML Markup code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Detect_Tab_Key.aspx.cs" Inherits="Detect_Tab_Key" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Check detect user entered Tab Key</title>
    <script type="text/javascript">
    function DetectTab(e) 
    {
    var KeyCode = (e.which) ? e.which : e.keyCode
    if(KeyCode==9)
        {
            alert("You have pressed Tab Key.");
        }
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox runat="server" ID="txt" onkeydown="DetectTab(event)"></asp:TextBox>
    </div>
    </form>
</body>
</html>

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

Script tested for:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

1 comments:

Anonymous said...

How can I send an 'TAB key' when I press an ENTER KEY

if(KeyCode==13)
{
//HERE I WANNA SEND A TAB KEY
}

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash