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


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Enter Escape Button</title>
    <script src="" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            var $inp = $('input:text');
            $inp.bind('keydown', function(e) {
                var key = (e.keyCode ? e.keyCode : e.which);
                var nextIndex = 0;
                if (key == 13) {
                    nextIndex = $inp.index(this) + 1;
                    $(":input:text:eq(" + nextIndex + ")").focus();
                else if (key == 27) {
                    nextIndex = $inp.index(this) - 1;
                    $(":input:text:eq(" + nextIndex + ")").focus();
    <form id="form1" runat="server">
    <div class="controlList">
            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 />

No comments:

Post a Comment