Tuesday, June 19, 2007

Auto Set Focus to Next control

You may want to auto set the focus to the next textbox, when the user has typed the exact length in the current textbox.
For example:
Telephone number: (012)-(12345678)
The max length for the first textbox is 3, after user typed in "012" which already reached the max length, the the focus should automatically set to the next text box.

Thanks for my colleague, Carmen, who helped me to find the following solution.

Add the following script to the <head> block:

Copy this function in the code file:
public static void AddNextTabAttribute(TextBox txt1,
TextBox txt2)
//Set next tab attribute when key up
txt1.Attributes.Add("OnKeyUp", "Tab(this, '" +
txt2.ClientID + "')");

Whenever the "KeyUp" event has trigged in the first textbox, it'll call the Tab() function and check if it has reached its max length.

Then, call this function in Page_Load event to add the attributes to the textbox.
AddNextTabAttribute(txtPhoneNo1, txtPhoneNo2);

That's it!
I am not sure if there is a better way to do this, I find that it's very powerful to combine Javascript in ASP.NET.

1 comment:

  1. Can anyone recommend the best RMM software for a small IT service company like mine? Does anyone use Kaseya.com or GFI.com? How do they compare to these guys I found recently: N-able N-central remote pc access
    ? What is your best take in cost vs performance among those three? I need a good advice please... Thanks in advance!