简体   繁体   中英

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!

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();"

Wouldn't jQuery's .ready() method work?

$(document).ready(function() {
    $('#target').focus();
});

请尝试使用Page.RegisterClientScriptBlock:

Page.RegisterClientScriptBlock("SetFocus", "<script>document.getElementById('" + this.tbAdjust.ClientID + "').focus();</script>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM