howto refer to servercontrol from javascript

  • Thread starter Thread starter Beffmans
  • Start date Start date
B

Beffmans

HI

I have the following javascript in my usercontrol:
function ClientValidation(source, args)
{
args.IsValid = document.getElementById("CheckBox1").checked;
}

this does not work? it's a usercontrol with 1 checkbox and I wanna test
whether it's checked!

ch B.
 
View the source on your page to find out the real ID of the control.
ASP.NET will generate a new ID for the control so it can be uniquely
identified on the page. If you were to have two instances of your control
on the page, how would the JavaScript "know" which one you mean? The
generated ID will generally take the form of _parentControlName_controlName;
_ctl0_CheckBox1, for example.

HTH
 
And the this ID is called ClientID property of the control on the server
side, so you can get it and store it somewhere in the page.
 
ok something like:

args.IsValid =
document.getElementById("WebUserControl11_CheckBox1").checked;

that doesn't work either?

ch B
 
it works, but it is fragile : if you change anything in the hierarchy (make
for instance any enclosing tag runat="server") you are (silently) screwed.
If the script is in the aspx page you can try using <%CheckBox1.ClientID%>.
 
Yes, ClientID. Since the CheckBox is in a UserControl, you may consider
emitting the javascript from the control with RegisterClientScriptBlock or
RegisterStartupScript. If you need to use the control multiple times on the
same page, make sure you check IsClientScriptBlockRegistered() before your
call to one of the Register methods.

RegisterClientScriptBlock:
http://msdn.microsoft.com/library/d...uipageclassregisterclientscriptblocktopic.asp

RegisterStartupScript:
http://msdn.microsoft.com/library/d...mwebuipageclassregisterstartupscripttopic.asp

IsClientScriptBlockRegistered:
http://msdn.microsoft.com/library/d...geclassisclientscriptblockregisteredtopic.asp

Sorry I forgot to mention the property in my previous post. I guess I just
got ahead of myself.

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top