jQuery Selectors and ASP.Net Controls 19
As I’ve already mentioned, this is the bane of jQuery within an ASP.Net application. Selecting the control based on its ID becomes difficult with ASP.net Controls and even worse with naming containers. There have been a few methods I’ve used to find the ASP.Net control in the dom.
Injecting the ClientID
$(“#<%= fooTextBox.ClientID %>”)
This is my least favorite, but the most precise. There are no additional elements or attributes to add and you’re guaranteed to get the exact control you’re after. Another bad side effect is the javascript has to be inside the ASPX page. That’s not ideal either, although you could argue that having a small script that just has variables for the control names isn’t that bad.
var fooTextBoxClientID = “<%= fooTextBox.ClientID %>”;
Still icky.
Add Custom Attribute
You could add a custom ID in the markup of the control.
<asp:TextBox runat=”server” id=”fooTextBox” myID=”foo” />
Then select on that custom ID.
$(“input[myID=’foo’]”)
This seems to make the code less DRY, but it works well.
Find With Ending
Since the name you give you .Net control is only prepended with its naming garbage, you can still find your names using the ends with selector.
$(“input[ID$=’fooTextBox’]")
This works well when the controls are assured to appear only once of the form; however, when inside a repeating control such as a ListView or a reusable control, this method falls apart.
Find With Class
I probably use this method more than any other since most of the time I have a parent frame of reference which limits the scope enough that makes my class name unique. That scope limiter also helps with the other methods, but using class names has worked the best for me.
$(“.inputTextBox")
Be careful not to use the CSS class like you would ID and create a CSS class for every element.
Wrap in HTML Elements
Also, you can wrap the control in an HTML element that will provide you full control over its ID.
<span id=”fooText”><asp:TextBox runat=”server” ID=”FooTextBox” /> </span>
Then select it using the child / ancestor selector.
$(“#fooText > input”)
You’re adding unneeded markup here, but you might already have it and just need to add the ID attribute, or select it using the class name.
I hope this helps with some headaches surrounding ASP.Net and jQuery.
Update: Since then, I’ve been using the following method more and more. The only change I’ve made is I’ve started to prefix my control name with the “_” to make sure I’m not picking up any control names that might carry similar ending names.
Like…
$(“input[ID$=’_PhoneTextBox’]")
and…
$(“input[ID$=’_CellPhoneTextBox’]")
Without the “_” both would match the following.
$(“input[ID$=’PhoneTextBox’]")