Get the Client ID of an ASP.NET Control in jQuery

While navigating the DOM using jQuery, it is often necessary to get the id of the control and perform operations on it, like hiding the control.

However, if you are using an ASP.NET Master Page and would like to retrieve the ClientId of a control using jQuery, then here's how to do so:


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


<title></title>


<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>


<script type="text/javascript">


    $(document).ready(function() {


        $("#<%=RadioButtonList1.ClientID %>").hide('slow');


    });    


</script>


</head>


<body>


<form id="form1" runat="server">


<div>   


<asp:RadioButtonList ID="RadioButtonList1"  runat="server">


<asp:ListItem Value="Ten"></asp:ListItem>


<asp:ListItem Value="Twenty"></asp:ListItem>


<asp:ListItem Value="Thirty"></asp:ListItem>


<asp:ListItem Value="Forty"></asp:ListItem>


</asp:RadioButtonList>




The example shown above fetches the ClientId of the RadioButtonList and hides it using jQuery




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

jQuery beginner said...

I'm trying to use the above to hide control, but get bellow error message:

$("#<%=dropDownNotification.ClientID %>").hide();
TypeError: Cannot set property 'display' of undefined

my control look like this:

<asp:DropDownList ID="dropDownNotification" runat="server">
<asp:ListItem Value="0" Text="Begge" Selected="True" />
<asp:ListItem Value="1" Text="SMS" />
<asp:ListItem Value="2" Text="E-mail" />
</asp:DropDownList>

The only way I seem to get hold of the control is to get it's full name from the source code:

$("#ctl00_ContentPlaceHolder1_dropDownNotification").hide();

Just don't think it is as pretty. Anyone who can help?!

Suprotim Agarwal said...

Are you getting this error in all browsers or just in Chrome?

jQuery beginner said...

you're right... at least it works in explorer. Thanks!