March 14, 2013

Hit Enter to move forward and Escape to backword

This post is to about some JavaScript stuff in order to gain some decent style of tab index changes. Sometimes people are searching of code in which when user hit enter tab index move forward and move backword when escape button press. 

Let's do this using simple and easy to understand JavaScript.

You should know following keycodes

  • For Enter Key    = 13
  • For Escape Key = 27

ASPX MARKUP:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EnterEscapeButton.aspx.cs"
    Inherits="Test_Web.EnterEscapeButton" %>

<!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>Enter Escape Button</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    
        $(function() {
            $('input:text:first').focus();            
            var $inp = $('input:text');
            $inp.bind('keydown', function(e) {
                var key = (e.keyCode ? e.keyCode : e.which);
                var nextIndex = 0;
                
                if (key == 13) {
                    e.preventDefault();
                    nextIndex = $inp.index(this) + 1;
                    $(":input:text:eq(" + nextIndex + ")").focus();
                }
                else if (key == 27) {
                    e.preventDefault();
                    nextIndex = $inp.index(this) - 1;
                    $(":input:text:eq(" + nextIndex + ")").focus();
                }
            });
        });
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="controlList">
        <h2>
            Hit Enter to move next and Escape to move back</h2>
        <br />
        <asp:TextBox ID="TextBox1" runat="server" /><br />
        <asp:RequiredFieldValidator ID="ReqUserName" runat="server" ErrorMessage="Enter Username" Text="*"
            ControlToValidate="TextBox1" Display="Dynamic" ForeColor="#993333"></asp:RequiredFieldValidator>
        <asp:TextBox ID="TextBox2" runat="server" /><br />
        <asp:TextBox ID="TextBox3" runat="server" /><br />
        <asp:TextBox ID="TextBox4" runat="server" /><br />
    </div>
    </form>
</body>
</html>