Long time ago, When I started to work with ASP.NET 2.0, I was very engry with MS because most of the Server-Side controls changed their names in the client side:'imgbtnFind' in the code-behind became 'ctl00_cphMPContent_imgbtnFind' in the client side, etc... (as I remeber, it wasn't like this in ASP.NET 1.1) How the Fu-- we can write JavaScript code that works with those controls??? If the JS code is in the page, we can use '<%= imgbtnFind.ClientID %>', but what if the JS code is in external .js file ?
'We have a problem Houston!'
I came up with the following function, and I can't write even single JS function without using it:
// for server-side controls that .NET change their names)
function $getElement( elementID, elementIndex ){
if( document.getElementById(elementID) )
return document.getElementById(elementID);
var reg = new RegExp( elementID + "$" );
var counter = 0;
var pageElements = document.getElementsByTagName("*");
for(i = 0; i < pageElements.length; i++) {
elm = pageElements[i];
if( elm.id ) {
if ( reg.test(elm.id) ) {
if( typeof(elementIndex) == 'number' ) {
if( counter == elementIndex ) { return elm; }
}else { return elm; }
counter ++;
}
}
}
Just place it in your javascript file that common to all your pages (as usualy web application have), and you can freely use $getElement(elementID) instead of document.getElementById(elementID) - for client side controls and for server-side controls as well. The rendering process in the aspx page concatenate all the parents containers names to the prefix of the control, So that function is checking for the suffix of the control name. The only thing to take care is to don't have two controls that complete server name of one is the exact suffix of the other, Or if you must to, you can use the second parameter of the function to control duplicate names... So now, to use the server control 'imgbtnFind' in the client side, just use $getElement('imgbtnFind') ...
Happy coding !