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.
Listing – 1
<%@ 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 id="Head1" runat="server">
<title>Check/Uncheck All CheckBoxes Using JQuery</title>
<script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>
</head>
<body>
<form id="form2" 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>
Listing – 2
<script type="text/javascript">
$(document).ready(function() {
$('#chkAll').click(function() {
$("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
});
});
</script>
Now add items programmatically to the CheckBoxList by using the following code at the Page load event:
Listing – 3
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
cbList.Items.Add(new ListItem("Items 1", "Items 1"));
cbList.Items.Add(new ListItem("Items 2", "Items 2"));
cbList.Items.Add(new ListItem("Items 3", "Items 3"));
cbList.Items.Add(new ListItem("Items 4", "Items 4"));
cbList.Items.Add(new ListItem("Items 5", "Items 5"));
}
}
Hope this will help !!!
Jay Ganesh