How to find Dynamic control in Java Script created using asp.net
I have created dynamic controls in ASP.NET as following ..
first i have created checkbox as
CheckBox chkDynamic = new CheckBox();
Then
TextBox txtDynamic = new TextBox();
txtDynamic.ID = "txtDynamic";
and these controls added in tablecell added in tableRow added in Table added in aspPanel(Only panel created at design page)
Now what i need.. when checkbox is selected i want to clear the txtDynamic Textbox using JavaScript
I tried following ways but not working..
chkDynamic.Attributes["onclick"] = "javascript:document.getElementById('" + txtDynamic.UniqueID + "').value='';";
also i tried with calling Method as
chkDynamic.Attributes.Add("onclick", "javascript:ClearText(this)");
but in t开发者_如何学编程his method following line giving me error not found "txtDynamic".. because the control added dynamicaly.
document.getElementById("<%= txtDynamic.ClientID %>").value="";
Thanks in advance....
After lots of debug i fond the answer. What does ASP.Net do at the run time it changes the ClientID of the control with attaching the parent control some prefix so before i added the entire table at the end of the all the TR created now what i did to solve this i have added the table to panel as plDynamicControls.Controls.Add(tblGeneralControls);
then i added following code and it works like charm
chkDynamic.Attributes["onclick"] = string.Format("yearSuffixCHK(this, '{0}')", txtDynamic.ClientID);
txtDynamic.Attributes["onchange"] = string.Format("yearSuffixTXT(this, '{0}')", chkDynamic.ClientID);
Have you ensured that your textbox has been loaded into the DOM when this script is getting executed?
I would recommend registering the uniqueID/Client id of the control in a javascript variable from server side.
Then on client side after the whole DOM is loaded bind the click event on the checkbox and then do respective work of cleaning up the textbox
(you can ensure that the DOM has loaded either by writing the script at end of page or using document.ready in case you use jQuery)
Thanks,
Pranav Kauhik
pranavkaushik.wordpress.com
When are you inserting the controls? If you do it in Page_Load it won't work. I would suggest inserting the controls in Page_Init (or Page_PreInit) if you are not already.
Also, use ClientID and not UniqueID because UniqueID can contain the colon character (:), which is not valid in the HTML ID attribute (and is not allowed in variable names in client-side script).
精彩评论