Move the cursor from 1 textbox to the other automatically

Assuming you have this simple scenario (normally apply to phone number or personal identification card number). You have a phone number. Normally the phone number is broken into 2 sections. The 1st section is the country code say 91 (India). And the other section is for your numbers assigned to you say (9988 0011). You can do this in 1 textbox for sure, but your boss wants some fancy. He/she asks you to break into 2 textboxes. Assuming you have entered 60 in the 1st textbox, when you press the 3rd character which is 9 it will move the cursor automatically into the 2nd textbox. I am using the JavaScript way. Thanks to a few people who recommends me this way. Just take note, by default when you create a textbox in Visual Studio 2005, there is no onKeyPress event in the intellisense. So you have to manually inject the code like this below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MoveTextbox.aspx.cs" Inherits="MoveTextbox" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head id="Head1" runat="server">
   <title>Untitled Page</title>

   <script type="text/javascript">
       function Length_TextField_Validator() {
           if (document.getElementById('<%= TextBox1.ClientID%>').value.length > 1) {
               document.getElementById('<%= TextBox2.ClientID%>').focus();
               return (false);
           return (true);


   <form id="form_name" runat="server">
       ASP.NET version<br />
       <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MoveTextbox : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        // Since by default, 2.0 textbox does not have the onKeyPress event

        // through intellisense, you have to do this way :P

        TextBox1.Attributes.Add("onKeyPress", "return Length_TextField_Validator()");


Post a Comment


Close Menu