Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery for find text box in ASP.NET page

Tags:

jquery

c#

asp.net

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?
}
like image 275
msophie Avatar asked Dec 10 '22 17:12

msophie


2 Answers

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.

like image 98
LBushkin Avatar answered Jan 14 '23 21:01

LBushkin


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);
}
like image 28
Luke Lowrey Avatar answered Jan 14 '23 22:01

Luke Lowrey