There are times that we need to use the enter key instead of using the Tab key for moving the focus of the TextBox controls from one to another to perform rapid data entry in the page. This example shows on how to achieve that with the use of JavaScript.
Here are the code blocks below:
ASPX:
<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Demo</title> </head> <script type="text/javascript" language="javascript"> function controlEnter (obj, event) { var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; if (keyCode == 13) { document.getElementById(obj).focus(); return false; } else { return true; } } </script> <body> <form id="form1" runat="server"> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox> <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox> </form> </body> </html> |
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e) { TextBox1.Attributes.Add("onkeypress", "return controlEnter('" + TextBox2.ClientID + "', event)"); TextBox2.Attributes.Add("onkeypress", "return controlEnter('" + TextBox3.ClientID + "', event)"); TextBox3.Attributes.Add("onkeypress", "return controlEnter('" + TextBox4.ClientID + "', event)"); TextBox4.Attributes.Add("onkeypress", "return controlEnter('" + TextBox5.ClientID + "', event)"); TextBox5.Attributes.Add("onkeypress", "return controlEnter('" + TextBox1.ClientID + "', event)"); } |
That’s it! Hope you will find this example useful!