Search This Blog

Sunday, April 8, 2012

Check/Uncheck all Items in an ASP.NET CheckBox List using jQuery


When the user clicks the checkbox, we run a function which finds all elements of the checkbox type and sets the ‘checked’ value of all items in the CheckBoxList to true or false based on the checked value of the ‘chkAll’ checkbox.
If you have multiple checkboxlist on your page, you can pass the CheckBoxList name and id as a parameter to the jQuery function as shown here:
 $("INPUT[@name=" + name + "][type='checkbox']").attr('checked', $('#' + id).is(':checked'));
The entire code with the finalized approach (Approach 3) will look similar to the following:
<%@ 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>

No comments:

Post a Comment