Today we are going to see how to make all the checkboxes checked when the user clicks the top checkbox ie., (Select All checkbox) . This script is really easy and is often needed in many situation.
Here is the Select All Function, this script has only two lines 🙂
$(function(){ $("#selectall").change(function () { $(".mycheckbox").prop('checked', $(this).prop('checked')); }); });
#selectall is the top checkbox (selectAll) when the user click the element it will see the other checkboxes are selected or not.
if no then it will select all, if yes, then it will deselect all.
.mycheckbox is the class used in all the other checkboxes.
Moreover, If the user manually select all the other checkboxes then we need to select the top check box right?. Here is the script for that.
// find if all the checkboxes are checked, if then select the top one too. $(".mycheckbox").change(function(){ if($(".mycheckbox").length == $(".mycheckbox:checked").length) $("#selectall").attr("checked", "checked"); else $("#selectall").removeAttr("checked"); });
Here is the Usage example code (just double click and copy the entire script in notepad, save it as html and test yourself):
<html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <title>"Select All" Checkboxex using jQuery</title> <script language="javascript"> $(function(){ // select all / deselect all $("#selectall").change(function () { $(".mycheckbox").prop('checked', $(this).prop('checked')); }); // find if all the checkboxes are checked, if then select the top one too. $(".mycheckbox").change(function(){ if($(".mycheckbox").length == $(".mycheckbox:checked").length) $("#selectall").attr("checked", "checked"); else $("#selectall").removeAttr("checked"); }); }); </script> </head> <body> <h2>"Select All" Checkboxex using jQuery</h2> <table style="border: 1px solid gray;"> <tr style="background:blue; color:white;"> <th ><input type="checkbox" id="selectall"/></th> <th align="left">Fruits</th> </tr> <tr> <td align="center"><input type="checkbox" class="mycheckbox" name="mycheckbox" value="1"/></td> <td>Apple</td> </tr> <tr> <td align="center"><input type="checkbox" class="mycheckbox" name="mycheckbox" value="2"/></td> <td>Orange</td> </tr> <tr> <td align="center"><input type="checkbox" class="mycheckbox" name="mycheckbox" value="3"/></td> <td>Mango</td> </tr> <tr> <td align="center"><input type="checkbox" class="mycheckbox" name="mycheckbox" value="4"/></td> <td>Papaya</td> </tr> <tr> <td align="center"><input type="checkbox" class="mycheckbox" name="mycheckbox" value="5"/></td> <td>Straberry</td> </tr> </table> </body> </html>
Here is the demo for you:
Working Code chackbox good……….