简体   繁体   中英

Setting focus on a text box on page load

I have already tried the information in How do you automatically set the focus to a textbox when a web page loads?

 <asp:TextBox ID="tbSearchLastName" runat="server" style="float:right" CssClass="search" tabindex="1" meta:resourcekey="tbSearchLastNameResource" />

                        <script type="text/javascript">
                            window.onload = function () {
                                document.getElementById("tbSearchLastName").focus();
                            };
                        </script>

I want the page focus to be on the textbox when the page loads but I am getting the error:

"Unable to get value of the property 'focus': object is null or undefined"

Thanks.

你必须这样做......

document.getElementById('<%= tbSearchLastName.ClientID%>').focus();

The ID you give your TextBox (or any .NET control, for that matter) is not the same ID that gets rendered in the HTML. To get the correct ID, you need to do:

 document.getElementById("<%=tbSearchLastName.ClientID %>")

Or, if you are in .NET 4, you can force it to keep the same ID

 <asp:TextBox ID="tbSearchLastName" ClientIDMode="Static" runat="server"/>

check in source of your page (in browser) what is the real id of tbSearchLastName. Probably it is not loaded or has been changed

Why don't you just put tbSearchLastName.Focus() in the code behind in the page_load method?

http://msdn.microsoft.com/en-us/library/system.web.ui.control.focus.aspx

protected void Page_Load(object sender, EventArgs e)
{
    Form.DefaultFocus = "tbSearchLastName";
}
protected void Page_Load(object sender,EventArgs e){
tbSearchLastName.focus();
}

you can try this on aspx.cs file ,its simple and elegant

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