tags:

views:

181

answers:

3

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?
}
+11  A: 

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.

LBushkin
+1, I didn't know about the client ID issue, though the malformed selector wouldn't help :)
Alastair Pitts
It's a deeply frustrating aspect of ASP.NET that you can't control the client-side ID. Thankfully, this is being addressed in ASP.NET 4.
LBushkin
You could just do what the 'lead developer' at my job does: replace all of the properly coded `<%= lastName.ClientID %>` tags with the full client-side id generated by ASP.NET, then wonder why reusable controls are no longer reusable ;D
Jim Schubert
+1  A: 

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);
}
Luke Lowrey
+1  A: 

You can do a partial attribute query:

<script type="text/javascript">

$(function() {

        $('#btnExtract').click(
            function() {
                alert($("input[id$='txtMessage").val());
            }
        );

    });

Selecting ASP.NET Web Controls in jQuery

Chris Love
yeah this is much better than my solution
Luke Lowrey