简体   繁体   中英

Call a ascx Javascript function from .aspx page

I have the following .ascx page(user control):

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MultiSelectDDL.ascx.cs" Inherits="MultiSelectDDL" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
 <link href="Styles/style.css" rel="stylesheet" type="text/css" />
<script type = "text/javascript">

    function CheckItem(checkBoxList) {
        debugger;
        var options = checkBoxList.getElementsByTagName('input');
        var arrayOfCheckBoxLabels = checkBoxList.getElementsByTagName("label");
        var s = "";

        for (i = 0; i < options.length; i++) {
            var opt = options[i];
            if (opt.checked) {
                s = s + ", " + arrayOfCheckBoxLabels[i].innerHTML;
            }
        }
        if (s.length > 0) {
            s = s.substring(2, s.length);
        }
        var TxtBox = document.getElementById("<%=txtCombo.ClientID%>");
    TxtBox.value = s;
    document.getElementById('<%=hidVal.ClientID %>').value = s;
}
</script>


<asp:TextBox ID="txtCombo" runat="server" ReadOnly="true" Width="138px" Font-Size="X-Small" CssClass="txtbox"></asp:TextBox>
<cc1:PopupControlExtender ID="PopupControlExtender111" runat="server" 
    TargetControlID="txtCombo" PopupControlID="Panel111" Position="Bottom" >
</cc1:PopupControlExtender>

<input type="hidden" name="hidVal" id="hidVal" runat="server" />

<asp:Panel ID="Panel111" runat="server" ScrollBars="Vertical" Width="142px" Height="75" BackColor="White" BorderColor="Gray" BorderWidth="1">

    <asp:CheckBoxList ID="chkList" 
        runat="server" 
        Height="75" onclick="CheckItem(this)">                                                                                                                                                                        
    </asp:CheckBoxList>

</asp:Panel>

And another normal .aspx page, in which I have placed the above user control.

What I need to do is, from a function written in .aspx.cs I want to call the Javascript written in .ascx page.

I tried:

 Page.ClientScript.RegisterStartupScript(this.GetType(),"MyFunction","CheckItem('"+ MultiSelectDDL1.ClientID +"');",true);

but it does not work. Plz help.

我认为问题在于您传递的是字符串而不是DOM元素,您应该使用以下内容更改启动脚本。

Page.ClientScript.RegisterStartupScript(this.GetType(),"MyFunction","CheckItem(document.getElementById('"+ MultiSelectDDL1.ClientID +"'));",true);

您需要传递客户端ID插入的对象

 Page.ClientScript.RegisterStartupScript(this.GetType(),"MyFunction","CheckItem(this);",true);

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