joncodo
joncodo

Reputation: 2328

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.

Upvotes: 2

Views: 12886

Answers (6)

Mac D&#39;zen
Mac D&#39;zen

Reputation: 151

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

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

Upvotes: 0

Christian
Christian

Reputation: 3972

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

Upvotes: 1

Justin
Justin

Reputation: 6549

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

Upvotes: 1

Matt
Matt

Reputation: 41832

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"/>

Upvotes: 2

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

You have to do like...

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

Upvotes: 5

i100
i100

Reputation: 4666

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

Upvotes: 1

Related Questions