Creating UserControls

205 Views Asked by At

This code works fine if I use it inside a normal page (e.g. Default.aspx). I want to use this in a UserControl.

How can I do this?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Check/Uncheck All CheckBoxes Using JQuery</title>

    <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
             });
         });    

     </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:CheckBox ID="chkAll" runat="server" Text="Check All" /><br />

        <asp:CheckBoxList ID="cbList" runat="server">
        </asp:CheckBoxList>

    </div>
    </form>
</body>
</html>
2

There are 2 best solutions below

0
On

The checkboxes have a different client ID when placed in a User Control, prepended by the ID of the User Control. Try modifying your jQuery as follows:

$(document).ready(function() {
   $('#<%=chkAll.ClientID %>').click(
    function() {
        $("INPUT[type='checkbox']").attr('checked', $('#<%=chkAll.ClientID %>').is(':checked'));
    });
});   
0
On

There are a lot of complexities in creating script-enabled UserControls, e.g. ASP.NET - JQuery

Generally: You need to make your script naming-container safe. References by DOM ID need to be made to the ASP.NET client ID (@FarligOpptredn's answer), or, alternatively, use CSS selectors (unless the functionality you are creating is specific to an instance).

Ideally, create all your client script in a JS file and register it from codebehind using ScriptManager. This allows the script to be re-used and avoids conflicts between instances of the UserControl. Since you can't use scriptlets (<%= ... %>) in a JS file, instead, use parameters to refer to objects in the UserControl DOM, or use CSS selectors. And use this in events instead of hard refs. Example

myUserControl.js:

 $(document).ready(function() {
            $('.myUserControl > .chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $(this).is(':checked'));
             });
         }); 

myUserControl.ascx:

<div class="myUserControl">

    <asp:CheckBox ID="chkAll" class="chkAll" runat="server" Text="Check All" /><br />

    <asp:CheckBoxList ID="cbList" runat="server">
    </asp:CheckBoxList>

</div>

This will make your script easier to read and debug, too, versus inline script with lots of escaping.