focusing on a textbox

  • Thread starter Thread starter Steven Zilberman
  • Start date Start date
S

Steven Zilberman

Is there a way to focus on a textbox in ASP.Net?
Can I do something like textBoxMyTextBox.Focus() ???
Meaning, I can't do it with the JavaScript way, because
JavaScript does not know the form name, and for some
reason it does not see the id of the textbox. Thank you.
 
For some reason it's not working. My asp code looks like
this:
<form runat="server">
<asp:TextBox id="UserName" runat="server" MaxLength="10"
Width="120px"></asp:TextBox>
</form>

The JavaScript code looks like this:
<script language="JavaScript">
<!--
window.document.all("UserName").focus();
//-->
</script>

I am getting a javascript error which says that
window.document.all(...) is a null or not an object.

Thanks.

Steven
 
Hi

Probably the element is not ready/loaded on the client when you call
focus....
Try changing the script to this... should be easy to modify to focus on any
element...

<script language="JavaScript">
<!--
function doFocus(){
if(document.forms[0].UserName) document.forms[0].UserName.focus();
}
onload = doFocus;
//-->
</script>



--
Best Regards
Vidar Petursson
==============================
Microsoft Internet Client & Controls MVP
==============================
 
For some reason it's not working. My asp code looks like
this:
<form runat="server">
<asp:TextBox id="UserName" runat="server" MaxLength="10"
Width="120px"></asp:TextBox>
</form>

The JavaScript code looks like this:
<script language="JavaScript">
<!--
window.document.all("UserName").focus();
//-->
</script>

I am getting a javascript error which says that
window.document.all(...) is a null or not an object.

Steven,

Look at the browser's HTML source for your page. I'll bet ASP.NET
modified the control name to something like _ctl0_UserName. ASP.NET
usually does this to controls in a UserControl (.ascx), so there
won't be a name collision if multiple instances of the same
UserControl are on the same page.

The way to fix this is to insert the JavaScript using server-side
code, and use the control's ClientId property to refer to the control
in the JavaScript code.

For example, you can put code like this in the Page_Load event of
your form (C#) to make the UserName TextBox control get focus:

string script = @"
<script language=""javascript"">
<!--
document.getElementById('{0}').focus();
//-->
</script>
";

if (!this.IsStartupScriptRegistered("SetWebControlFocus"))
this.RegisterStartupScript("SetWebControlFocus",
string.Format(script, UserName.ClientID));



Hope this helps.

Chris.
 
Back
Top