retrieve ID of server control using jQuery
Asked Answered
R

6

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 = ??
Roustabout answered 14/4, 2011 at 15:54 Comment(2)
Have a look at the HTML that generates. Not too sure on how ASP runat worksThoroughgoing
@Thoroughgoing is right, you can look at the HTML, or just use the clientID like I show below.Donnelly
A
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';
Afloat answered 14/4, 2011 at 16:38 Comment(4)
gotta love .net 4.0. the whole 'clientid" thing definitely caused some long hours of googling for me back in the day.Donnelly
Can add pages clientIdMode="Static" directive in web.config to have entire site do this.Guillen
Actually, shouldn't the js be var id = document.getElementById("label1"); ?Bijection
No, it just id, not the element itself.Afloat
D
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 %>';
Donnelly answered 14/4, 2011 at 16:1 Comment(1)
In your first example, I would rename 'id' to something else since it's a reference to the JQuery wrapper for the label element.Neology
S
3
var $lblObj = $("label[id$='label1']:first")
Stockholder answered 9/8, 2012 at 9:57 Comment(0)
S
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.

Surfperch answered 14/4, 2011 at 15:57 Comment(1)
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...Cairo
C
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

Crossexamine answered 23/11, 2011 at 9:11 Comment(1)
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 @Afloat or Jack Marchetti mentioned.Cairo
U
-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); 
        });
    });
Uninterested answered 14/4, 2011 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.