Accessing control from javascript could be quite trouble some when you are using MasterPage.
if you are having a TextBox in your page, the ClientID of the control will automatically generated as ctl00_ContentPlaceHolder1_TextBox1.
To make it easier, you can just simply hardcode the “ctl00_ContentPlaceHolder1_”
But, In my case hardcoding the “ctl00_ContentPlaceHolder1_” it’s not a good idea, Because the MasterPage could be Recursive, and the Page could use by many project ( using embedded resource and so-on). It will generated different ClientID when it’s being call by different Project.
here’s something you can do, to get the ClientID :
function showTextBoxClientId ()
{
var txtBox = ‘<%=TextBox1.ClientID%>’;
alert (txtBox);
}
But, what if the control is generated dynamically??, something like this..
The showHidePanel alert will only show “GeneratedPanel1″, without “ctl00_ContentPlaceHolder1_”
function ShowHidePanel(id) {
{
alert (id);
return false;
}
Then, here’s what I did in order to get it right..
function ShowHidePanel(id) {
var tempid = ”;
tempid = tempid.replace(‘TextBox1′, id);
obj = document.getElementById(tempid);
if (obj.style.display == ‘none’)
{ obj.style.display = ”; }
else
{ obj.style.display = ‘none’; }
return false;
}
I get the “ctl00_ContentPlaceHolder1_” from non dynamic control, and just replace the controlID with the control that we need.
Please download the whole code here
