简体   繁体   中英

Use jQuery for find text box in ASP.NET page

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);
}

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

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