Search code examples
c#javascriptjqueryasp.netcode-behind

SetFocus to Control From Code Behind with JavaScript


I am trying to set focus to a page control (Textbox) by using the registerStartupScript method. However, I have been unsuccessful. Here is what I have tried:

ClientScript.RegisterStartupScript(this.GetType(), "SetFocus", "<script>document.getElementById('" + this.tbAdjust.ClientID + "').focus();</script>");

And:

ClientScript.RegisterStartupScript(GetType(), "focus", "<script>$('" + this.tbAdjust.ClientID + "');</script>");

Can't seem to get it. Seems like a pretty straight forward question, if you all need anymore code, let me know. Thanks in advance for any help!


Solution

  • Normally tbAdjust.Focus(); at code behind should work. Here are the scripts.

    Without Ajax

    ClientScript.RegisterStartupScript(this.GetType(), "focus", 
    "document.getElementById('" + this.tbAdjust.ClientID + "').focus();", true);
    

    With Ajax

    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "focus", 
    "document.getElementById('" + this.tbAdjust.ClientID + "').focus();", true);
    

    If you want to use jQuery, you need # at the front.

    For example, "$('#" + this.tbAdjust.ClientID + "').focus();"