have a custom control with a button. There is an external javascript file that tries to attach some events to my control. Like onclick event is added at runtime to the button. To do so I use
var save = document.getElementById("btnExecute");
This control is being called from aspx page where I have attached the JS file. The page won't work, I read articles that it will work if I change the code to something like
var save = document.getElementById("<%= btnExecute.ClientID %>");
but it only works if the JS is within the aspx file. How to make this work for a custom control. What all steps do I need to follow to get the ID on external JS to work?
Tried Ajax81's solution: Code added
namespace MyCompositeControl
{
public class MyGrid : CompositeControl
{
public string ButtonClientID
{
get { return btnExecute.ClientID; }
set { }
}
protected override void CreateChildControls()
{
#region Execute Button
btnExecute.ID = "btnExecute";
btnExecute.Text = "Execute";
btnExecute.Click += new EventHandler(_button_Click);
Controls.Add(btnExecute);
#endregion
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string jsResourceName = "MyCompositeControl.Scripts.ControlScriptLibrary.js";
ClientScriptManager cs = this.Page.ClientScript;
cs.RegisterClientScriptResource(typeof(this,GetType()), jsResourceName);
}
}
The button is added dynamically as you can see in above code.
ControlScriptLibrary.js
function attachEvents()
{
//var save = document.getElementById("btnExecute");
var save = document.getElementById("<%=MyGrid.ButtonClientID%>");
if(save!=null)
{
save.onclick = onSaveAction;
}
}
Edited: Still it returns null. Can it be that, the JS runs first and the control is not yet there? But this works if I pass the control id like this:
function MyController(executeButtonID, onSaveEventHandler)
{
function attachEvents()
{
//var save = document.getElementById("btnExecute");
var save = document.getElementById(executeButtonID);
if(save!=null)
{
save.onclick = onSaveAction;
}
}
}
In my control's RenderContent method I have the following javascript code:
var myController = new MyController(this.btnExecute.ClientID, onSaveEventHandler);
This approach will kill if I have more buttons on the control and need some event handling in JS. Ajax81's solution is nice but it is not working for me yet.