Accessing Web Forms Controls with javascript

  • Thread starter Thread starter Red
  • Start date Start date
R

Red

Can you access web form control via javascript ie..

if I have <asp:textbox runat=server id=txtTextbox/>

can I say in javascript

txtTextbox.Enabled = true;

??
 
Personally, I could never get you using the ID attribute of a Web control to work with JavaScript. Instead, when you view the source of your web page from a Web browser you will see that the server automatically assigns the Web control a ClientID the usually begins, at least in my experience, something line "_ctl0_<ID attribute value>". Since the Enabled property is server side I'm not sure that you would be able to control it like that using JavaScript. However, a workaround could be to set the display attribute of the controls style property to 'block' if you wanted it to be visible and 'none' if you wanted it to be not visible. A sample JavaScript code would be

function ShowControl (controlID)
var element = document.getElementById (controlID)
//to show the element use the followin
element.style.display = 'block'
//to hide the element use the followin
element.style.display = 'none'


However, the above function works well in Internet Explorer, but the earlier versions of Opera does not support the display property, so you would have to use the visibility attribute instead as follows

function ShowControl (controlID)
var element = document.getElementById (controlID)
//to show the element use the followin
element.style.visibility = 'visible'
//to hide the element use the followin
element.style.visibility = 'hidden '


I hope this helps
Ji
 
That was what I was looking for. Thanks alot.
Jim Mace said:
Personally, I could never get you using the ID attribute of a Web control
to work with JavaScript. Instead, when you view the source of your web page
from a Web browser you will see that the server automatically assigns the
Web control a ClientID the usually begins, at least in my experience,
something line "_ctl0_<ID attribute value>". Since the Enabled property is
server side I'm not sure that you would be able to control it like that
using JavaScript. However, a workaround could be to set the display
attribute of the controls style property to 'block' if you wanted it to be
visible and 'none' if you wanted it to be not visible. A sample JavaScript
code would be:
function ShowControl (controlID) {
var element = document.getElementById (controlID);
//to show the element use the following
element.style.display = 'block';
//to hide the element use the following
element.style.display = 'none';
}

However, the above function works well in Internet Explorer, but the
earlier versions of Opera does not support the display property, so you
would have to use the visibility attribute instead as follows:
 
Back
Top