by Arra Derderian
27. October 2010 00:23

Having to select .NET controls via jQuery is easy because you can specify a unique class name for whatever control you want to select and use the "." selector to find that element on the client side. The problem is the class selector is slower than the id selector and it also breaks the rules of separating functionality and design. You end up with class names that may get stripped out by a CSSS developer later on. You also have the extra markup required on every element for this class name.
Hoping to find some way to select elements based on .NET id I Googled around and found the following code which adds a custom selector to the jQuery ":" selector called "asp".
Solution 1
jQuery.expr[':'].asp = function (elem, i, match) { return (elem.id && elem.id.match(match[3] + "$")); };
Here we return any elements that have an ID and secondly, end with the id string specified. You would call this code like this:
Calling It
$(":asp(SelectTextBox)")
After looking at this I noticed that because we are using the "EndsWith" regex match that we will get any control with an ID that ends with "SelectTextBox". This is a problem because if we have a control called "NewSelectTextBox" and then another called "SelectTextBox" they both will be selected. So I looked at the .NET markup generated from these two controls existing on the same page and saw that an underscore("_") was preceding the final controls .NET ID on the client. I then came up with solution #2.
Solution 2
jQuery.expr[':'].asp = function (elem, i, match) { return (elem.id && elem.id.match("_" + match[3] + "$")); };
Seems like an easy fix. This would eliminate any similarly named controls. Well there is one last problem that I am still working on getting around. That is that if you nest one of these textboxes in a custom control for example, it will print out the textbox id ending with the same "_ID" and add the parent controls name to the front of it. If there is two of these custom controls on a page you will have to unique controls on the page, but they will both end with "_SameName". I am still wondering how to solve this issue. Perhaps we add more logic to the custom selector to only return the first found element? What do people think? I mean in these situations you would probably want multiple controls returned anyways because you would be modifying all the items or you could combine the selector with a ":first" if you wanted. You probably would end up generating some sort of extra markup for uniqueness as well because the items will most likely represent an ID in your database. Anyways, I thought I would share this and see if anyone had any ideas on it.