In this tutorial i explains how to select and deselect multiple check box using jquery.
First you have to include a jQuery Libarary
1 |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> |
HTML Code for Check boxes
1 2 3 4 5 6 7 8 9 10 |
<ul class="main"> <li><input type="checkbox" id="select_all" /> Select all</li> <ul> <li><input type="checkbox" class="checkbox" value="1"/>Ejiro</li> <li><input type="checkbox" class="checkbox" value="2"/>Ogbugbu</li> <li><input type="checkbox" class="checkbox" value="3"/>Kefe</li> <li><input type="checkbox" class="checkbox" value="4"/>Vovwe</li> <li><input type="checkbox" class="checkbox" value="5"/>Grace</li> </ul> </ul> |
#select_all is the id for check box and items checkboxes have a checkbox class.
Jquery Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<script type="text/javascript"> $(document).ready(function(){ $('#select_all').on('click',function(){ if(this.checked){ $('.checkbox').each(function(){ this.checked = true; }); }else{ $('.checkbox').each(function(){ this.checked = false; }); } }); $('.checkbox').on('click',function(){ if($('.checkbox:checked').length == $('.checkbox').length){ $('#select_all').prop('checked',true); }else{ $('#select_all').prop('checked',false); } }); }); </script> |
Demo
- Select all
- Ejiro
- IOgbugbu
- Kefe
- Vovwe
- Grace
Here is the full code that we have written during this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><script type="text/javascript"> $(document).ready(function(){ $('#select_all').on('click',function(){ if(this.checked){ $('.checkbox').each(function(){ this.checked = true; }); }else{ $('.checkbox').each(function(){ this.checked = false; }); } }); $('.checkbox').on('click',function(){ if($('.checkbox:checked').length == $('.checkbox').length){ $('#select_all').prop('checked',true); }else{ $('#select_all').prop('checked',false); } }); }); </script> <ul class="main"> <li><input type="checkbox" id="select_all" /> Select all</li> <ul> <li><input type="checkbox" class="checkbox" value="1"/>Item 1</li> <li><input type="checkbox" class="checkbox" value="2"/>Item 2</li> <li><input type="checkbox" class="checkbox" value="3"/>Item 3</li> <li><input type="checkbox" class="checkbox" value="4"/>Item 4</li> <li><input type="checkbox" class="checkbox" value="5"/>Item 5</li> </ul> </ul> |