<asp:TextBox ID="myTextBox" runat="server" />
can cause the TextBox to be rendered as:
type="text" id="ctl00_ContentPlaceHolder1_myTextBox" />
First, the Hack
var myValue = document.getElementById('<%= myTextBox.ClientID %>');
this will render as
var myValue = document.getElementById('ctl00_ContentPlaceHolder1_myTextBox');
This technique has a couple of huge shortcomings:
- It is really hard to maintain
JQuery to the Rescue...sort of
One of the main features of using the JQuery library, is its use of selectors to find elements on the page. I will not get that deeply into this rich DOM querying language here, but you can read all about it from the JQuery Documentation.
JQuery selectors allow me to find items in the page many different ways. For example, I can find the textbox in my example above using the following code:
var myTextBox = $("input:text");
This will actually find every textbox on the page but since we have only on textbox on our page, it works. Alternatively, you can use something like the Css class of the item. Suppose we gave the textbox a css class of 'textInput':
<asp:TextBox ID="myTextBox" runat="server" CssClass="textInput" />
Now, the control renders as:
var myTextBox = $("input:text[@class=textInput]");
var myTextBox = $("input.textInput");
or even simpler
var myTextBox = $(".textInput");
There are many ways to select the same item, but you get the idea.
var myTextBox = $("#ctl00_ContentPlaceHolder1_myTextBox");
<asp:TextBox ID="myTextBox" runat="server" ClientSelector="myTextBox" />
I just use a made up attribute called 'ClientSelector' (you can use whatever you fancy and it renders like this:
<input name="ctl00$ContentPlaceHolder1$myTextBox" type="text"
so now we can use JQuery to select the item with this statement
var myTextBox = $("input[@ClientSelector=myTextBox]");
So now we can use the same selector for just this one textbox no matter if it is in a MasterPage or not. We don't have to care how the id renders anymore. I have found this technique very useful. What do you think? Is this also too much of a hack?