Ok, so we all know that ASP.NET controls, or any control for that matter with the runat=”server” tag, will generate a funky client ID when rendered on the page.
Sometimes, we need to get at those controls via some client side javascript so that we may manipulate their properties or simply get/set their values.
If you’re not already familiar with JQuery, you need to take 5 minutes of your day and read up on it. It’s a very light javascript library that any decent developer should have in their toolbelt.
Now getting started with JQuery is pretty simple. It doesn’t matter what type of app you’re building, you simply need to download the jquery-1.3.2.min.js (this is the current version as of the time i wrote this post) file and include it in the HEAD tag your page:
1 | <script type="text/javascript" src="jquery-1.3.2.min.js"></script> |
Some examples of what you can do with JQeury (I got most of this from reading the documentation):
Example 1 – DOM Ready
1 2 3 4 | $(document).ready(function () { // execute any code here that you'd like to be run as soon as the dom is ready. You may often // want to show/hide certain controls on page load }); |
Example 2 – Determine if an ASP.NET radio button is checked
1 2 3 | var radio = $("#<%= radioButton.ClientID %>"); var domRadio = radio[0]; var isChecked = domRadio.checked; |
1 | <input type="radio" id="radioButton" name="age" value="20" runat="server" /> |
This is the most important part:
1 | $("#<%= radioButton.ClientID %>") |
radioButton.ClientID gets replaced with the automatically generated ASP.NET client id of this control. When I was working with prototypejs, I used to use the class selector to get a handle to these controls: $(”.className”) so naturally I started doing the same thing when I began working with JQuery. I wasn’t entirely happy with this method because it added what was otherwise an unnecessary property to my controls.
After discovering .ClientID, I use it most often. I still use the class selector but for different reasons. For example, if i want to show/hide a specific TR tag within a table, here is how I would do that:
Example 3 – Show/Hide
1 2 3 4 5 | if (isChecked) { $(".rowHide").hide(); } else { $(".rowHide").show(); } |
1 2 3 | <tr class="rowHide">
<td>some data</td>
</tr> |
Example 4 – Set the url for a link tag
1 2 3 | $("#<%= link.ClientID %>").attr({ href: "/pages/mypage.aspx?id=" + id; }); |
<a id="link" target="_blank" runat="server">My Link</a>
I’ll be writing a post that describes in detail how to leverage JQuery to build autocomplete functionality into your SharePoint applications. Some users prefer the ASP.NET Ajax route, but in my humble opinion, JQuery is far easier to configure and use.
If anyone would like to see that sooner, just ping me and I’ll send some notes of how I achieved this.
3 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
Continuing the Discussion
You must be logged in to post a comment.