Search code examples
javascriptasp.netascx

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.


Solution

  • I think the problem is you are passing a sting instead of an DOM element you should change you start up script with the below one.

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