Reputation: 1056
I have a page where it is getting overwhelmed with code like:
var textBox = $get("<%=textState.ClientID%>");
This requires me to have my JavaScript inside the page instead of nicely tucked in a js file. Is there a better approach to this?
document.getElementById doesn't work because then I end up with code like this:
var textBox = document.getElementById("originDestinationControl_textState");
or
var textBox = document.getElementById("ctl00_ContentPlaceHolder_originDestinationControl_textState");
depending on where I am referencing these controls (inside master pages and/or usercontrols)
Upvotes: 3
Views: 1204
Reputation: 1816
I normally stick something like this into pages where I want to use a separate js file.
<script type="text/javascript">
var pageNameElements = {
textbox : '<%= textbox.ClientId %>',
button : '<%= button.ClientId %>'
};
</script>
This way you get a nice javascript object with all the control ids that you can use in your js file like this.
$('#' + pageNameElements.textbox)
or
document.getElementById(pageNameElements.textbox)
if you're not using jquery.
Upvotes: 3
Reputation: 7306
Might I suggest learning jQuery? Since I started using it I have never once had to deal with messy asp tags to get at controls on the page.
var textBox = $get("<%=textState.ClientID%>");
would look something like
var textBox = $("input[id$='_textState']");
in jQuery. And even better, you can place it into it's own js file!
Upvotes: 2
Reputation: 7713
I think you're stuck.
Your textState.ClientId code needs to stay on the aspx page itself. This is because it's rendered client side. JavaScript include files are downloaded separately from the rest of the page, so it won't know how to handle it.
If you need to clean this up, you could try using classic asp style include files. However, in asp.net they end up adding more of a mess than they fix.
Upvotes: 0
Reputation: 21178
With .NET 4.0 you actually have total control over this:
http://www.codeproject.com/KB/aspnet/ASP_NET4_0ClientIDFeature.aspx
It has hit Release Candidate along with Visual Studio 2010. I know this isn't an ideal solution, but it is one.
http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx
Upvotes: 1