I've create a basic composite server control that contains a button.
<Custom:Class1 ID="testClass" ClientInstanceName="test1" runat="server"></Custom:Class1>
I would like to be able to get to the child controls using javascript for example:
var myButton = testClass.FindControl('btnTest');
Is there anyway to do this?
Create a client side object to represent your server side control (javascript class). Put a collection of references to the child controls on the client side object. Then on the server side OnPreRender event create or load a script to define your client side object and at the same time pass the collection of references to its constructor.
Example of how to embed a javascript file containing the clientside object definition (put this somwhere above the namespace declaration:
[assembly: WebResource("myNS.stuff.clientSideObj.js", "application/x-javascript")]
namespace myNS.stuff
{
Example of how to register the WebResouce (OnPreRender):
ClientScriptManager cs = this.Page.ClientScript;// Get a ClientScriptManager reference from the Page class.
Type csType = this.GetType();// Get the type from this class.
//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
String resourceName1 = "myNS.stuff.clientSideObj.js";
cs.RegisterClientScriptResource(csType, resourceName1);
Example of creating a script to declare an instance of your client side object (OnPreRender):
String childControlIDsList= getChildControlList();//I am not writing this one.. just look up javascript arrays.
String uniqueScriptKey = "myKey";
StringBuilder theScript = new StringBuilder();
theScript.AppendLine("var myObj = new clientSideObj(" + childControlIDsList + ");");
theScript.AppendLine("window['myClientControl'] = myObj;") //create a client side reference to your control.
cs.RegisterStartupScript(csType, uniqueScriptKey, theScript.ToString(), true);
I will leave the client side object definition up to you... Hope that helps!