Focus on next TextBox using jQuery and ASP.NET

I am in love with enter key on keyboard, so when while filling long form many time after entering information I hit enter key. Wouldn't it be nice if I hit enter key and instead of form posting back or submitting form it moves to next textbox. Today we will try to achieve this using jQuery in ASP.NET page. Below is what our end result will look like:

Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TextBoxEnterbox.aspx.cs" Inherits="TextBoxEnterbox" %>

 

<!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">

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<title></title>

<script type="text/javascript">

 

$(document).ready(function() {

// Setting focus on first textbox

$('input:text:first').focus();

// binding keydown event to textbox

$('input:text').bind('keydown', function(e) {

// detecting keycode returned from keydown and comparing if its equal to 13 (enter key code)

if (e.keyCode == 13) {

// by default if you hit enter key while on textbox so below code will prevent that default behaviour

e.preventDefault();

// getting next index by getting current index and incrementing it by 1 to go to next textbox

var nextIndex = $('input:text').index(this) + 1;

// getting total number of textboxes on the page to detect how far we need to go

var maxIndex = $('input:text').length;

// check to see if next index is still smaller then max index

if (nextIndex < maxIndex) {

// setting index to next textbox using CSS3 selector of nth child

$('input:text:eq(' + nextIndex+')').focus();

}

 

}

});

});

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

First Name: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

Last Name: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

Email: <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

Confirm Email: <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

<asp:Button ID="btnSubmit" runat="server" Text="Submit" />

</div>

</form>

</body>

</html>

Tags: , , , ,

ASP.NET | jQuery