ASP.NET 2.0 – 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 60 (Malaysia). 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:

 

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

 

Simple right. Basically Length_TextField_Validator() is a JavaScript function in the html code.

 

Below is the sample code.

 

Default.aspx

 

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

 

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

    <title>Untitled Page</title>

 

    <script language="javascript">   

        <!--

            // Check the length of the textbox

            function Length_TextField_Validator()

            {

                if ((form_name.TextBox1.value.length > 2))

                {               

                    form_name.TextBox2.focus();

 

                    return (false);

                }

 

                return (true);

            }

        -->

    </script>

 

</head>

<body>

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

        <div>

            ASP.NET version<br />

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

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

        </div>

    </form>

</body>

</html>

 

Default.aspx.cs

 

using System;

using System.Data;

using System.Configuration;

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 _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        // Since by default, asp.net 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()");

    }

}

 

Have fun J

Published Friday, December 29, 2006 11:29 AM by chuawenching