Many times I see folks struggling with a problem like this:
I really want to get at an ASP.NET control with JavaScript but once the control has rendered, the ID of the control gets mangled to look something like
ctl00_Content_foo_bar. How do I go about working with this control in JavaScript since the ID is dynamically generated?
There are many possible solutions to this problem:
- Hard-code this ID into your JavaScript code.
- Generate your JavaScript code in your code-behind as a string so that you can embed the ID dynamically.
- Add a CSS class to the control and use something like jQuery’s CSS selectors to find our control (other JavaScript frameworks have similar methods).
- Find some way to pass the ID down to the JavaScript by squirreling it away in a hidden input or invisible element.
While these solutions may work they are far from ideal. Here are the problems I see:
- The practice of hard-coding is brittle and any changes to your ASP.NET code could potentially break your JavaScript code.
- This solution has potential but still is ugly since you now have to maintain your JavaScript as a string and since the code no longer lives in a separate file, browsers will no longer be able to cache your JavaScript locally.
- Finding an element by a CSS class sacrifices performance to work (it is much slower than selecting by ID).
- This final solution has promise as well but requires a lot of plumbing and extra markup to accomplish something that should be simple.
Here is a better solution:
Wrap your ASP.NET control’s markup in a plain HTML element and give that element an ID.
Here is an example:
<div id="fooWrapper">
<asp:textbox id="foo" runat="server"/>
</div>
Now that you have wrapped your control in an HTML element that is not set to be runat="server", its ID will not be mangled when the page is rendered. This means you can retrieve the textbox by first finding its parent and then finding the next immediate child element of type input.
Here is how I would do it using jQuery:
textBox = $("#fooWrapper input:text");
I truly believe this is the simplest and most straightforward solution to this problem and it will also provide better performance that most other options.
3 Comments
For quick one-off tasks, I find this the easiest method:
textBox = $(”);
It’s not pretty, but it gets the job done with a minimum of hassle.
Of course, it makes no sense when the comment system strips out your < and %gt; characters and everything in between. :P
Sorry Bryan – the commenting system must have removed parts of your code to a place where even I can’t see it! I am very interested to see your solution so feel free to shoot me an email (andrew at togaroga.com) if you get a chance.
Post a Comment