Using jQuery to find a text field on an ASP.NET page
You have two different problems that you need to solve: the wrong selector and the fact that the server identifiers do not match in the identifiers of the ASP.NET client.
What would you like:
$.ready() { $('#<%= lastName.ClientID %>').focus(); } Let me break it ...
First, in jQuery, a selector that accesses an element using the id attribute must begin with a "#" character. Thus, the accessory should look larger: $('#lastName') . Selectors in jQuery are similar, but more reliable than in CSS. You can read the selector syntax on the jQuery API site.
Second, with ASP.NET, the identifier assigned to HTML elements is often different from the identifier that identifies the asp control on the server. This is because ASP.NET needs to make sure that all elements are uniquely identified - and do not encounter names that can be defined on main pages, user controls, or repeating sections of content. These identifiers tend to become long and often impossible to predict - fortunately, we can use the code extension <%= %> along with the ClientID property of the control to insert the corresponding identifier for the HTML element without having to know the details of how ASP.NET assigns unique identifiers.
In ASP.NET 4.0, the client ID can now be specified directly, which can help avoid the technique shown above.
Here is the function that I use to select server controls on the pages with the main page. It does not work in all cases, such as nested controls, but for simpler things, it is really convenient.
It happens on the main page somewhere
<script type="text/javascript"> baseName = "<%= Content.ClientID %>_"; </script> With this function you can go GetServerElementById ("lastname")
function GetServerElementById(id) { return $("#" + baseName + id); }