ASP.Net and JQuery - How to check/uncheck all items in a CheckBoxList
This is a second post in a new series of posts regarding ASP.Net and JQuery. You can see the first post here.
I will try to present JQuery samples in this series of posts that will be most useful to asp.net developers.
In this second post I will show you how to check/uncheck all items in a CheckBoxList using JQuery.
We will demonstrate this with a step by step example. I will use Visual Studio 2010 Ultimate. You can also use Visual Studio 2008 if you do not have Visual Studio. Express editions work fine. 1) Create an ASP.Net website. Choose an appropriate name for your site. 2) Now we have the default web site ready. We will add some web server controls in the default.aspx page 3) The markup should look like this
<h3>Check/Uncheck all checkboxes</h3><br />
<asp:CheckBox ID="chkAllNone" runat="server"
Text="Check/Uncheck All" />
<br /><hr />
<asp:CheckBoxList ID="chkList" runat="server" class="chk">
<asp:ListItem Text="One" Value="One" />
<asp:ListItem Text="Two" Value="Two" />
<asp:ListItem Text="Three" Value="Three" />
<asp:ListItem Text="Four" Value="Four" />
</asp:CheckBoxList>
We will use the first checkbox to check/uncheck all the items in the checkbox list.
4) In the Site.master file before the </head> tag add this line of code Then we do set the "checked" value of the referenced elements to true or false based on the value of the CheckAllNone.<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
5) In the <head> section of the Site.master page we need to add the actual JQuery code that makes the checking/unchecking of all the items in the checkbox list possible.
<script type="text/javascript">
$(function () {
var $chkBoxAllNone = $("input:checkbox[id$=chkAllNone]");
var $tblChkBox = $("table.chk input:checkbox");
$chkBoxAllNone.click(function () {
$tblChkBox
.attr('checked', $chkBoxAllNone
.is(':checked'));
});
$tblChkBox.click(
function (e) {
if (!$(this)[0].checked) {
$chkBoxAllNone.attr("checked", false);
}
});
});
</script>
var $chkBoxAllNone = $("input:checkbox[id$=chkAllNone]");
var $tblChkBox = $("table.chk input:checkbox"); $chkBoxAllNone.click(function () {
$tblChkBox
.attr('checked', $chkBoxAllNone
.is(':checked'));
});
I have tested this JQuery example with all the modern browsers.Please note that you do need to have a basic understanding of JQuery to fully understand this and the following JQuery & Asp.net tutorials. Hope it helps.