I have <asp:TextBox runat="server" ID="lastName" />
on a page and I want to set focus it with jQuery but it is not returning it. My code is like this:
$.ready() {
var tb = $('lastName').focus(); // don't work, why?
}
You have two different problems here that you need to resolve: a malformed selector and the fact that in ASP.NET client IDs don't match server IDs.
What you want is:
$.ready() {
$('#<%= lastName.ClientID %>').focus();
}
Let's break it down...
First, in jQuery a selector that accesses an element by it's id
attribute needs to begin with a '#' symbol. So the accessor should look more like: $('#lastName')
. Selectors in jQuery are similar, but more robust than in CSS. You can familiarize yourself with the selector syntax at the jQuery API site.
Second, with ASP.NET, the id's assigned to the HTML elements are often different than those that identify an asp control on the server. This is because ASP.NET needs to make sure that all elements are uniquely identified - and don't collide with names that may be defined in master pages, user controls, or repeated sections of content. These ids tend to get long and are often impossible to predict - fortunately, we can use the <%= %>
code expansion together with the ClientID
property of the control to insert the appropriate id for the HTML element without having to know the details of how ASP.NET assigns unique ids.
In ASP.NET 4.0, the client ID can now be specified directly, which can help avoid the technique shown above.
Here is a function I use for selecting server controls in pages that have a masterpage. It doesnt work in all cases such as nested controls but for simpler stuff its real handy.
This goes on the masterpage somewhere
<script type="text/javascript">
baseName = "<%= Content.ClientID %>_";
</script>
Using this function you can go GetServerElementById("lastname")
function GetServerElementById(id) {
return $("#" + baseName + id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With