Find an element by id within a dynamically added control

家住魔仙堡 提交于 2019-12-11 18:38:42

问题


I have an asp page in which I add dynamically a control I created (several times). In that control I have textbox for password and username and a revert button.

I use this javascript code in that control and it fails:

function HandlePasswordChanged() {
    document.getElementById("<%=btnRevert.ClientID %>").disabled = false;
}
function HandleUserChanged() {
    document.getElementById("<%=btnRevert.ClientID %>").disabled = false;
    document.getElementById("<%=txtPassword.ClientID %>").disabled = false;
}
function btnRevertClick() {
    document.getElementById("<%=btnRevert.ClientID %>").disabled = true;
    document.getElementById("<%=txtPassword.ClientID %>").disabled = true;
    document.getElementById("<%=txtUsername.ClientID %>").value = document.getElementById("<%=systemAccount.ClientID %>").value;
    document.getElementById("<%=txtPassword.ClientID %>").value = "";
}

what it does is when I press the revert button on one control it disables the textbox on the other control - getelement fails to find the correct one.

How can I fix this?


回答1:


If you are working on .net 4.0:

You can set ClientIDMode="Static" for your dynamically added controls. Also, you have to make sure you set unique ids for your controls.




回答2:


I managed to find the solution.

The problem was that every time I added the acsx control with the javascript code it added multiple functions with the same name but the inside was different. when one control wanted to call its "own" function it just used the first one since they were all named the same.

My solution was to change the function from this:

function HandleUserChanged() {
    document.getElementById("<%=btnRevert.ClientID %>").disabled = false;
    document.getElementById("<%=txtPassword.ClientID %>").disabled = false;
}

to this:

function HandleUserChanged(btnRevertId, txtPasswordId, cellPasswordId) {
    document.getElementById(btnRevertId).disabled = false;
    document.getElementById(txtPasswordId).disabled = false;
}

and then in the c# code I add this:

txtUsername.Attributes.Add("onchange", "HandleUserChanged(\"" + btnRevert.ClientID + "\", \"" + txtPassword.ClientID + "\", \"" + cellPassword.ClientID + "\")");

This way each control know exactly which controls belong to him and sends the correct parameters to the function.



来源:https://stackoverflow.com/questions/15967372/find-an-element-by-id-within-a-dynamically-added-control

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