retrieve ID of server control using jQuery

21,495

Solution 1

If you use ASP.NET 4.0 you can set attribute ClientIDMode="Static" and your code will looks following way:

<asp:Label ID="label1" runat="server" ClientIDMode="Static"></asp:Label>

js:

var id = 'label1';

Solution 2

var labelID = $('#<%= label1.ClientID %>');

You need to get the client ID.

If you just need the ID, and not the actual value of the control, then you don't even need jQuery.

var labelID  = '<%= label1.ClientID %>';

Solution 3

var $lblObj = $("label[id$='label1']:first")
Share:
21,495
AGuyCalledGerald
Author by

AGuyCalledGerald

I am a .Net web developer with eager interest in HTML 5, CSS 3, jQuery and all tools and techniques that help enhance frontend development. I also like graphic design.

Updated on August 10, 2020

Comments

  • AGuyCalledGerald
    AGuyCalledGerald almost 4 years

    How do I get the ID of a server control with jQuery?

    E.g. I have

    <asp:Label ID="label1" runat="server""></asp:Label>

    and now I want to get "label1",

    var id = ??
    
  • Eric Falsken
    Eric Falsken about 13 years
    In your first example, I would rename 'id' to something else since it's a reference to the JQuery wrapper for the label element.
  • Jack Marchetti
    Jack Marchetti about 13 years
    gotta love .net 4.0. the whole 'clientid" thing definitely caused some long hours of googling for me back in the day.
  • Eric Burdo
    Eric Burdo about 11 years
    That approach gets ugly, the more "nesting" you have. ASP Panels, User Controls, Master Pages, etc all add to the ID value. You either need to use a pure jQuery approach, and get the control that "ends with" your ControlID value, or use the approach @pstarkov or Jack Marchetti mentioned.
  • Eric Burdo
    Eric Burdo about 11 years
    True, jQuery runs on the client side. However, ASP does some funky stuff to the IDs of controls with the runat tag. So you can't just use the ID. It changes at runtime...
  • adrian.andreas
    adrian.andreas almost 11 years
    Can add pages clientIdMode="Static" directive in web.config to have entire site do this.
  • Krondorian
    Krondorian over 10 years
    Actually, shouldn't the js be var id = document.getElementById("label1"); ?
  • pstarkov
    pstarkov over 10 years
    No, it just id, not the element itself.