Select/Deselect ASP.NET CheckboxList using jQuery

Providing multiple checkboxes on page is very common when collecting information/interest from user. Having one additional checkbox to select all checkboxes is a very interesting and compelling functionality and is very easy to achieve with jQuery.

Snapshot of final product:

 

Code:

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

 

<!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></title>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script type="text/javascript">

$(document).ready(function() {

// binding check all to click

$('#CheckBox1').click(function() {

// Collecting all checkboxes within checkboxlist1

var allCheckboxes = $('#CheckBoxList1 input[type=checkbox]');

// Iterating over all checkboxes in above collection

$.each(allCheckboxes, function(index, val) {

// Deselecting checkboxes

if (($('#' + val.id).is(':checked')) && ($(this).is(':checked'))) {

$('#' + val.id).attr('checked', false);

 

}

// Selecting checkboxes

else if ((!$('#' + val.id).is(':checked')) && (!$(this).is(':checked'))) {

$('#' + val.id).attr('checked', true);

 

}

});

 

});

});

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

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

<asp:CheckBoxList ID="CheckBoxList1" runat="server">

<asp:ListItem>Newsletter</asp:ListItem>

<asp:ListItem>Email</asp:ListItem>

<asp:ListItem>RSS Feed</asp:ListItem>

<asp:ListItem>Twitter</asp:ListItem>

<asp:ListItem>Facebook</asp:ListItem>

</asp:CheckBoxList>

</div>

</form>

</body>

</html>

Tags: , , , , , , , ,

ASP.NET | jQuery