ColoradoYo
ColoradoYo

Reputation: 33

Could not access asp.net control ID in jquery

I have this html structure:

<asp:Panel ID="divOne">
  <div class="divSection1">
  <asp:Panel runat="server" id="specialId" class="ClassOne ClassTwo"
    <asp:Label  id="MyLabel"></asp:Label>
    <div id="myDiv" </div>
  </asp:Panel>
  </div>
</asp:Panel> 

And i am trying to access the "specialId" in jquery like $('#specialId'), $('div.specialId') with no success. Can someone advice?

Upvotes: 2

Views: 9200

Answers (2)

Venkata Krishna
Venkata Krishna

Reputation: 15112

My similar answer with a little more explanation is here

runat="server" in asp.net adds master and page information to each of its control. So, if you look at the DOM, your control would look something like this master_page_ctrl0_specialId[just an example].

You have a few options.

Option1: Use the client ID - recommended but meh.. not so much. I would try to avoid writing ClientID in javascript as much as possible.

$('#<%= specialId.ClientID %>')

Option2: Using the same ID - not recommended because its really ugly.

$('[id$=specialId]') or $('[id*=specialId]')

The above selectors are any id which ends with specialID and any id which contains specialId respectively.

Option3: Using the class - highly recommended. Because selectors using classes are clean and uncomplicated. Also, I see you've used class, use CssClass instead for .net controls.

$('.ClassOne.ClassTwo')

Option4: Use ClientIDMode="Static", which got introduced in .NET Framework 4.0, on the control so that its ID will stay unchanged. - recommended too.

<asp:Panel runat="server" ClientIDMode="Static" id="specialId" CssClass="ClassOne ClassTwo">
</asp:Panel>

Upvotes: 6

Chirag Vidani
Chirag Vidani

Reputation: 2577

You should use actual generated HTML id using below syntax

That means you need to use client ID which can be accessed via below syntax

$('#<%= specialId.ClientID %>')

Upvotes: 1

Related Questions