How to set the input focus?

C

Caspy

How to set the input focus to a specific textBox in a form when browser a
web page?

thanks,
--Caspy
 
A

Alvin Bruney [MVP]

I use this code

public static void SetInitialFocus(System.Web.UI.Control control)
{
if (control.Page == null)
{
throw new ArgumentException("The Control must be added to a Page before
you can set the IntialFocus to it.");
}

if (control.Page.Request.Browser.JavaScript == true)
{
// Create JavaScript
System.Text.StringBuilder s = new System.Text.StringBuilder();
s.Append("\n<SCRIPT LANGUAGE='JavaScript'>\n");
s.Append("<!--\n");
s.Append("function SetInitialFocus()\n");
s.Append("{\n");
s.Append(" document.");

// Find the Form
System.Web.UI.Control p = control.Parent;
while (!(p is System.Web.UI.HtmlControls.HtmlForm))
p = p.Parent;

s.Append(p.ClientID);
s.Append("['");
s.Append(control.UniqueID);
// Set Focus on the selected item
System.Web.UI.WebControls.TextBox rbl = control as
System.Web.UI.WebControls.TextBox;
s.Append("'].focus();\n ");
s.Append("}\n");

if (control.Page.SmartNavigation)
s.Append("window.setTimeout(SetInitialFocus, 500);\n");
else
s.Append("window.onload = SetInitialFocus;\n");

s.Append("// -->\n");
s.Append("</SCRIPT>");

// Register Client Script
control.Page.RegisterClientScriptBlock("InitialFocus", s.ToString());
}
}

I no longer remember if I authored this code or if I stole it from somewhere
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top