Remove Name Mangling from ASP.Net Master Pages (get your ID back!) August 18
If you have been programming using ASP.Net Master Pages and javascript then you have no doubt come across the problem where you try to access an element in javascript using:
var sValue = document.getElementById(’TextBox1′).value;
And you keep getting an error that the element cannot be found. If you check the HTML source for the page, you see that asp.net has “helpfully” added something like ‘ctl00_ContentPlaceHolder1_’ to the front of the control ID, so you have to use:
var sValue = document.getElementById(’ctl00_ContentPlaceHolder1_TextBox1′).value;
I’m not going to try & sugar coat it - this totally sucks.
The solution that I have been using overwrites the .getElementById method, allowing you to search for the element just using the normal ID.
<script type='text/javascript'>
document.newGetElementById = document.getElementById;
document.getElementById = function(sElementID)
{
var oFirstTry;
oFirstTry = document.newGetElementById(sElementID);
if (oFirstTry)
return oFirstTry;
else
return document.newGetElementById('ctl00_ContentPlaceHolder1_' + sElementID);
}
</script>
Thanks to Scooby Doo for pointing out the earlier error, it has now been corrected
Add this code to the top of your asp.net page or .js file, and then you can go back to using:
var sValue = document.getElementById(’TextBox1′).value;
without caring if it is in a content page or not.
Note: The above code won’t work if you change the name of your ContentPlaceHolder control from the standard ‘ContentPlaceHolder1′. If you do like to have unique names then change
return document.getElementById(’ctl00_ContentPlaceHolder1_’ + sElementID);
to
return document.newGetElementById(’<%=me.Form.Controls(1).ClientID %><%=Me.ClientIDSeparator %>’ + sElementID);
The code must now always be placed in your asp.net page (not an external .js file). However, calls to .getElementById can still be in external .js files.
Finally: A common solution to the problem is to use the ClientID property:
var sValue = document.getElementById(’<% =TextBox1.ClientID %>’).value;
but this method requires that all calls to getElementById be in the asp.net page, which is not as flexible as the solution given.
This post brought to you by WeGotDomain.com - Over 10,000 Aged domains for sale!
Related posts:
