Mike Borozdin's Blog

A blog about programming, web and IT in general

Follow Me

Search

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© 2014 Mike Borozdin

CSS Class Names Instead of ASP.NET Client IDs

In ASP.NET the client IDs of controls are often really unpredictable. When you need to add some JavaScript code that works with rendered controls you have to know their IDs. But usually an ID looks like something like this: “ctl00_contentBody_txtStreet”. There are several methods for overcoming that diffic ulty explained here. However they require writing additional code or even creating your own controls inherited from the original ones.

But there is one simply but yet dirty way of addressing HTML elements rendered by ASP.NET. Do you remember that you can assign the CssClass attribute to any server control? Do you remember the jQuery selector that allows you to retrieve the elements with the specified CSS class? So, we can use it!

The pattern is simple:

<asp:TextBox ID="txtStreet" runat="server" CssClass="txtStreet" />

You just add the CssClass attribute and give it a unique value.

Then you can retrieve the value of the element or perform any other manipulation with jQuery:

alert($('.txtStreet').val());

Pretty simple. Although you must remember that it can take some time in case you have a long page because it will look through all the HTML tags to find the one with the given class name. At the same time for fast execution you can specify which elements to look for, you can simply add a tag name before, for instance “input” or a jQuery attribute – “:input”:

alert($('input.txtStreet').val());

Kick it! Shout it

Tags:
Posted on Thursday, February 26, 2009
Comments (7)
blog comments powered by Disqus