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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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);
}
</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>
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, 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()");
}
}
Thursday, March 13, 2008
Move the cursor from 1 textbox to the other automatically
Labels:
ASP.NET
Subscribe to:
Post Comments (Atom)


No comments:
Post a Comment