Check / Uncheck all checkboxes using jquery

Here is simple code snippet in jquery to check and uncheck all checkboxes in jquery.
We need this when we have to perform action on multiple rows or datasets. So i have written very minimal code in jquery to check and uncheck multiple checkboxes.




check-uncheck
Sample Html

<!DOCTYPE html>
<html>
<head>
<title>Check/Uncheck all check box using jquery</title>
</head>
<body>
<table border="1">
<tr><th colspan=2><input type="checkbox" class="all">Check/Uncheck</th></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>India</td></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>Brazil</td></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>China</td></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>France</td></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>United States</td></tr>
</table>
</body>
</html>

After that include jquery library before body close tang and put some jquery to apply action.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
	$(function(){
       $('.all').click(function(){
          if($(this).is(':checked')) {
          	$("input[name='st[]']").prop('checked', true);
          } else {
          	$("input[name='st[]']").prop('checked', false);
          }
       });
	});
</script>

Where jquery .is() function return true or false as main checkbox is checked or unchecked



Now your complete index.html file will be..

index.html

<!DOCTYPE html>
<html>
<head>
<title>Check/Uncheck all check box using jquery</title>
</head>
<body>
 
<table border="1">
<tr><th colspan=2><input type="checkbox" class="all">Check/Uncheck</th></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>India</td></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>Brazil</td></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>China</td></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>France</td></tr>
<tr><td><input type="checkbox" name="st[]"></td><td>United States</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
	$(function(){
       $('.all').click(function(){
          if($(this).is(':checked')) {
          	$("input[name='st[]']").prop('checked', true);
          } else {
          	$("input[name='st[]']").prop('checked', false);
          }
       });
	});
</script>
</body>
</html>

DEMO

DOWNLOAD

If you like this post please don’t forget to subscribe my public note book for more useful stuff