graph
graph

Reputation: 387

using jQuery within asp.net control

I have a funny situation with a jquery selector, trying to find something within an asp.net LoginView:

Say I have 4 controls, 2 plain html <input>s, and 2 <asp:TextBox>es. One of each inside an <asp:Loginview>.

<asp:LoginView ID="LoginView1" runat="server">
    <LoggedInTemplate>
        <input type="text" id="htmlInput1" />
        <asp:TextBox id="aspTextbox1" runat="server"></asp:TextBox>
    </LoggedInTemplate>
</asp:LoginView>

<input type="text" id="htmlInput2" />
<asp:TextBox id="aspTextbox2" runat="server"></asp:TextBox>

Then let's say I want to apply some jquery to each of them. Guess which one of these 4 does not work?

 <script>
         $(function () {             
             $("#htmlInput1").datepicker();
             $("#htmlInput2").datepicker();
             $("#aspTextbox1").datepicker();  
             $("#aspTextbox2").datepicker();             
         });
 </script>

For some reason, the asp.net textbox within the LoginView is not reached. Do I have to somehow select the LoginView first?

var x = $("LoginView1")..... 

Upvotes: 0

Views: 346

Answers (2)

Devesh
Devesh

Reputation: 4550

The reason is ASP.NET auto generates the ID at run time which is not as same as you are trying to read in jQuery . Open the viewsource and look at the ID generated. You can use that Id , otherwise if you are using ASP.NET 4.0 or higher I think you can set the Id predictable. Read this: http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx For ASP.NET control

          $("#"+<%= Control.ClientID %>).val();

Upvotes: 1

Ant P
Ant P

Reputation: 25221

This is because server-side tags are given unique identifiers when they are rendered. If you open the rendered source of the page, you'll see that the element's id has been modified to contain the entire control hierarchy. Because of this, your jQuery selector will no longer find the element.

However, because they will always end with the specified id, you can use the jQuery attributeEndsWith selector:

$('[id$="aspTextbox1"]').datepicker();

Alternatively, give all of the elements you want to do this for a CssClass of datepicker and do:

$('.datepicker').datepicker();

This is probably a cleaner, less obtrusive way of achieving the same thing, as it allows you to call the datepicker method on all of those elements with a single line of code. Additionally, it allows you to add more datepicker elements by simply giving new elements the same class, rather than having to modify your jQuery every time:

<asp:TextBox id="aspTextbox999" CssClass="datepicker" runat="server" />

Upvotes: 1

Related Questions