2

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?

Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
ColoradoYo
  • 33
  • 1
  • 5
  • check this http://stackoverflow.com/questions/11389733/accessing-asp-net-controls-in-javascript . It does something similar – Surender Nov 08 '13 at 13:23
  • You should provide the actual generated HTML, and not your template code. – moonwave99 Nov 08 '13 at 13:23
  • What does the actual client-side HTML look like? JavaScript doesn't interact with your server-side code. – David Nov 08 '13 at 13:24
  • 1
    `runat="server"` seems to be missing on your tags. If possible, make a selection on the class. Or use the ClientID as stated by @ChiraqVidani – jbl Nov 08 '13 at 13:28

2 Answers2

6

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>
Community
  • 1
  • 1
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
  • 1
    There is also the overlooked 4th option of using Static ClientIDMode http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx – jbl Nov 08 '13 at 15:10
1

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 %>')
Chirag Vidani
  • 2,519
  • 18
  • 26