Easy Way To Select Deselect Checkboxes- jQuery

This is a simple tutorial which will guide you how to check/un-check checkboxes using jQuery. I consider here that you already know about use of checkboxes. This tutorial will cover how to select and deselect checkboxes using jQuery, If you want to select all boxes by checking “select all” and also want to select each individual checkboxes then this tutorial is for you.

A cool example of this you would have seen in your gmail inbox. Whenever you delete emails you use checkboxes there. want to delete all emails in a page just check “select all” box.

You can check LIVE DEMO here. It would also tell you number of boxes you have selected by alerting you with a message.

In my future posts I will show how to perform delete/insert operation on checkboxes that will be refelected in your database. Just like gmail does.

Here is our code:

<HTML>
<HEAD>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">

$('document').ready(function(){

$("#selectall").click(function () {
$('.td').attr('checked', this.checked);
alert("You have selected all boxes");
});

$(".td").click(function(){
alert("You have checked  "+$(".td:checked").length+"  boxes");
if($(".td").length == $(".td:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}

});
});
</script>
</HEAD>
<BODY>

<input type="checkbox" id="selectall"/><b>Subjects </b><br>
<input type="checkbox" class="td" />Maths  <br>
<input type="checkbox" class="td" />History  <br>
<input type="checkbox" class="td" />Computer Science  <br>
<input type="checkbox" class="td" />Science   <br>
<input type="checkbox" class="td" />Astrology  <br>

</BODY>
</HTML>

LIVE DEMO is well structured because it uses HTML <table> tag to arrange items in a tabular way. You can use above script in your web projects. Please share this tutorial to help other people. Email me or comment below to get the script of live demo in your Inbox.

5 thoughts on “Easy Way To Select Deselect Checkboxes- jQuery”

  1. I would like to update data in database using ajax when check box is checked
    could you please send me a link or code to help through it
    revert back ASAP

    1. Hi timchosen,

      Yes you can extend the funtionality of this simple script to delete selected(checked)records from database.

  2. Pingback: Get Multiple Checkbox Values in PHP - InfoTuts

Comments are closed.