简体   繁体   中英

Wrong javascript function called when ascx control added to page twice

I have a control that contains a javascript function that is called on the client click event of a button:

OnClientClicked="ClearTree" 

the function:

    function ClearTree() {
        var tree = $find('<%=cboOrgUnits.Items[0].FindControl("tvOrgUnits").ClientID %>');
        var nodes = tree.get_nodes();
        for (var i = 0; i < nodes.get_count(); i++) {
            nodes.getNode(i).uncheck();
        }
   };

Which all works fine except for when the control is on the same page twice. When it is there are 2 instances of the function 'ClearTree' of which it seems the second one added is always called.

The problem is that the instance of ClearTree() called might not be referencing the correct tree.

What are the possible workarounds for this?

Here is the rest of the markup:

<telerik:RadComboBox ID="cboOrgUnits" runat="server" Width="400px" ShowToggleImage="True" Style="vertical-align: middle;" EmptyMessage="Choose organisation units to group by" ExpandAnimation-Type="None" CollapseAnimation-Type="None">
<HeaderTemplate>
    <div>
        <span class="right" style="margin:2px"><telerik:RadButton ID="rbClear" runat="server" Text="Clear" Visible="True" OnClientClicked="ClearTree" AutoPostBack="False"/></span>
        <span class="right" style="margin:2px"><telerik:RadButton ID="rbDone" runat="server" Text="Done" Visible="True" OnClick="rbDone_Click"/></span>
        <div class="clear"></div>
    </div>
</HeaderTemplate>
<ItemTemplate>
    <div>
        <telerik:RadTreeView ID="tvOrgUnits" runat="server" CheckBoxes="true" Style="z-index: 100" CheckChildNodes="True">
            <Nodes>
            </Nodes>
        </telerik:RadTreeView>
    </div>
</ItemTemplate>
<Items>
    <telerik:RadComboBoxItem Text="" />
</Items>
</telerik:RadComboBox>

Instead of embedding the ClientID of the control inside your function, make it a function parameter, and then change your OnClientClicked to pass the ClientID to the function.

function ClearTree(id)
{
    var tree = $find(id);
    // ...
}
protected override void Render(HtmlTextWriter writer)
{
    rbClear.OnClientClicked = String.Format("ClearTree('{0}')", rbClear.ClientID);
    base.Render(writer);
}

UPDATE: Because rbClear is defined inside a template, you might need to call cboOrgUnits.FindControl("rbClear") to get a reference to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM