Shift Focus to the Next TextBox using the Enter Key using jQuery

Posted by: Suprotim Agarwal , on 7/12/2010, in Category jQuery and ASP.NET
Views: 87714
Abstract: In this short and simple article, we will see how to tab through the TextBoxes with the Enter Key using jQuery.
In this short and simple article, we will see how to tab through the TextBoxes with the Enter Key using jQuery.
This article is a chapter from my EBook called 51 Recipes with jQuery and ASP.NET Controls. The chapter has been modified a little to publish it as an article.
Note that for demonstration purposes, I have included jQuery code in the same page. Ideally, these resources should be created in separate folders for maintainability. The code shown below has been tested on IE7, IE8, Firefox 3, Chrome 2 and Safari 4.
Let us quickly jump to the solution to shift focus to the next TextBox using the Enter Key.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
    <title>Shift Focus to the Next TextBox when user presses Enter</title>
    <script type="text/javascript"
        src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
    </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.charCode);
                var key = e.which;
                if (key == 13) {
                    e.preventDefault();
                    var nxtIdx = $inp.index(this) + 1;
                    $(":input:text:eq(" + nxtIdx + ")").focus();
                }
            });
        });
    </script>
</head>
<body>
    <form id="form2" runat="server">
    <div class="smallDiv">
        <h2>Enter text and hit Enter to move to next text box</h2><br />
        <asp:TextBox ID="TextBox1" runat="server" /><br />
        <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>
This example uses the bind() function that binds one or more events to a handler. The key is detected using the e.which
var key = e.which
 
If the key == 13, i.e the Enter key is pressed, the default behavior (postback) is suppressed using e.preventDefault() and instead the index of the current textbox is retrieved. We then add 1 (one) to the index, to shift the focus to the next textbox.
if (key == 13) {
        e.preventDefault();
        var nxtIdx = $inp.index(this) + 1;
        $(":input:text:eq(" +nxtIdx + ")").focus();
}
 
This is how the user tabs through the textboxes when the Enter Key is pressed. Some data entry operators find it easier to use the Enter Key to tab through the input controls!
Note: If you plan to add textboxes at runtime and want this code to continue to work with the dynamically added textboxes, use live() instead of bind(). Remember that in each call, you cannot bind more than one event to live().
See a Live Demo
 
Shift Focus using Enter Between TextBox and TextArea
 
One of my EBook readers, Leny mailed asking how to shift focus between a TextBox and TextArea. Well the code shown above will not work in the case of a TextArea, since to select a textarea, you need to use $(‘textarea’) and we are using var $inp = $('input:text'). The best way to achieve this requirement will be to add a class(cls) to the elements as shown below:
    <head id="Head1" runat="server">
    <title>Shift Focus to the Next TextBox when user presses Enter</title>
    <script type="text/javascript"
        src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
    </script>
   
    <script type="text/javascript">
        $(function() {
            $('input:text:first').focus();
            var $inp = $('.cls');
            $inp.bind('keydown', function(e) {
                //var key = (e.keyCode ? e.keyCode : e.charCode);
                var key = e.which;
                if (key == 13) {
                    e.preventDefault();
                    var nxtIdx = $inp.index(this) + 1;
                    $(".cls:eq(" + nxtIdx + ")").focus();
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="smallDiv">
        <h2>Enter text and hit Enter to move to next text box</h2><br />
        <asp:TextBox ID="tb1" runat="server" class="cls" /><br />
        <asp:TextBox ID="tb2" runat="server" class="cls" /><br />
        <asp:TextBox ID="tb3" TextMode="MultiLine" runat="server" class="cls" /><br />
        <asp:TextBox ID="tb4" runat="server" class="cls" /><br />
    </div>
    </form>
</body>
</html>
Observe the change in these two lines of code:
var $inp = $('.cls');
and
$(".cls:eq(" + nxtIdx + ")").focus();
 
We are using the class cls to only work with the elements we are interested in. Now you can tab between the textbox and the textarea using an Enter Key.
I hope you found this article useful and I thank you for viewing it. This article was taken from my EBook called 51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls which contains similar recipes that you can use in your applications.
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Carol on Wednesday, July 14, 2010 4:23 AM
abc: Your comment was deleted as it was anonymous, based on wrong facts and was misleading. If you feel there is an error, use the contact page http://dotnetcurry.com/Contact.aspx
Comment posted by Your name is required on Monday, October 18, 2010 4:56 AM
The comment text is required
Comment posted by Hiren Sanchala on Saturday, November 20, 2010 12:23 AM
This Function is done but how to include drop down control to next focus
Comment posted by Hiren Sanchala on Monday, January 3, 2011 3:13 AM
This Focus function is work properly but its only work on textbox i need all control in asp.net.
Please send me this Solution
Thanks...
Comment posted by heti on Tuesday, April 19, 2011 8:08 PM
thanks a ton .. you saved my day .. i made it work with all input elements with a particular class .. works like a charm
Comment posted by Your name is required. on Monday, May 16, 2011 7:06 AM
very nice
Comment posted by Jayesh on Wednesday, May 25, 2011 8:35 AM
Really helpful. But there is a problem when the focus reaches the last textbox then the code doesn't check whether the textbox exists or not.

After doing some googling, I found this articles which does exactly the same thing. Take a look.

http://jquerybyexample.blogspot.com/2011/05/how-to-set-focus-on-next-textbox-on.html
Comment posted by Dorababu on Friday, April 20, 2012 7:55 AM
Assume I have some 4 text boxes and a Button how can I set focus on button after text boxes
Comment posted by hồng phước on Monday, July 30, 2012 9:48 PM
thankssssssssssssss !
Comment posted by Raja on Monday, October 1, 2012 2:35 AM

Above that working well in textbox k.
But when i am using one textbox with password mode that not working .
how. Any one help me
Comment posted by Nandashri on Wednesday, December 5, 2012 2:56 AM
Thanks a ton for this...was looking for it :)
Comment posted by vasanthi on Friday, October 25, 2013 6:37 AM
hi,i want to jump another controls in form if enter entering key.
your coding have same class in all form elements so it go next box easily.
i have different controls(like text box,radio,check box,drop down list ect..)it have different class name.
so i can not access next control so please help me sir.
i want your guide.thank.
Comment posted by rams on Sunday, December 15, 2013 4:03 AM
Successfully works.. thanks
Comment posted by rams on Sunday, December 15, 2013 4:11 AM
I created an online exam application in asp.net. I want disable print screen option, save page as option and view page source option(ctrl+u).can you help me?
Comment posted by jiv on Saturday, March 1, 2014 10:02 AM
lol. its not even working with the latest version of firefox.
Comment posted by kishor on Sunday, April 20, 2014 1:53 PM
Thanks for your nice article.but the problem is that i need to change my focus from textbox to combobox and again this combobox to textbox..please help........

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel