How to find Dynamic control in Java Script created using asp.net

坚强是说给别人听的谎言 提交于 2019-12-14 03:58:37

问题


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 this method following line giving me error not found "txtDynamic".. because the control added dynamicaly.

 document.getElementById("<%= txtDynamic.ClientID %>").value="";

Thanks in advance....


回答1:


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);



回答2:


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




回答3:


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).



来源:https://stackoverflow.com/questions/4012479/how-to-find-dynamic-control-in-java-script-created-using-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!