Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Setting focus using asp:button 1

Status
Not open for further replies.

dpdoug

Programmer
Nov 27, 2002
455
US
I want to be able to set the focus to a text box after clicking an asp:button. I can't get it to work using javascript and the onlick. It says that the function is not a member of asp.whatever

Does anyone know how this is done?
 
Code:
<script language=javascript>
  function setFocus(){
    document.getElementById(&quot;myTextBox&quot;).focus();
  }
</script>
...........
<asp:TextBox id=&quot;myTextBox&quot; runat=server />
<asp:Button ID=&quot;myButton&quot; runat=server Text=&quot;Set Focus&quot; />

code behind:
override protected void OnInit(EventArgs e)
{
  //
  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
  //
  InitializeComponent();
  base.OnInit(e);

  if(myButton.Attributes[''onclick''] == null)
  {
    myButton.Attributes.Add(&quot;onclick&quot;, &quot;javascript:setFocus()&quot;);
  }
}
This should do the trick.
 
I use this...it allows you to call it at any time pretty easily...

Code-Behind:

Private Sub SetFocus(ByVal ctrl As System.Web.UI.Control)
Dim s As String
s = &quot;<SCRIPT language = 'javascript'>document.getElementById('&quot; & ctrl.ID & _
&quot;').focus()</SCRIPT>&quot;
RegisterStartupScript(&quot;focus&quot;, s)
End Sub

Then you just call items like this

Page Load

SetFocus(txtFirstField)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top