7

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 = ??
Jack Marchetti
  • 15,026
  • 13
  • 73
  • 116
AGuyCalledGerald
  • 7,117
  • 16
  • 63
  • 110

6 Answers6

11

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';
pstarkov
  • 149
  • 5
9
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 %>';
Jack Marchetti
  • 15,026
  • 13
  • 73
  • 116
  • In your first example, I would rename 'id' to something else since it's a reference to the JQuery wrapper for the label element. – Eric Falsken Apr 14 '11 at 16:38
3
var $lblObj = $("label[id$='label1']:first")
j0k
  • 21,914
  • 28
  • 75
  • 84
Roman
  • 31
  • 1
0

jQuery runs on the client side so would only be able to access the ID of the html element rather than the asp control on the server.

Ira Rainey
  • 5,029
  • 2
  • 30
  • 41
  • 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... – Eric Burdo May 15 '13 at 11:59
0

Are you using master page. If yes give ContentPlaceHolderID along with control id.

Eg:

 jQuery("#ContentPlaceHolderID_ControlId").val;
   jQuery("#body_label1").text;

You can see this in Viewsource

selva
  • 781
  • 2
  • 12
  • 25
  • 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 May 15 '13 at 11:56
-1

Labels render as span tags. So if you want to select all the Labels:

    $(document).ready(function()
    {
        $Labels = $("span");

        $Labels.each(function()
        {
            alert(this.id); 
        });
    });
Steve Wellens
  • 20,160
  • 2
  • 24
  • 64