Home jQuery

Check or Uncheck Checkboxes with jQuery And Get Selected with PHP

jquery-tutorial

When you have a list of data, sometimes, you want to easily check all or uncheck all of them. And then process those selected/checked data by getting their values first.

Today we’re going to do something like what we’re using in GMail or YahooMail.

  1. Check or Uncheck All Checkboxes in a form (using jQuery).
  2. Get the selected checkboxes values when the form is submitted (using PHP).

Check or Uncheck Checkboxes with jQuery And Get Selected with PHP

In case you want instant testing you may download the code or see the result in live demo:

<html>
	<head>
		<title>Check and Uncheck All</title>
	</head>
<body>

<div style='margin: 10px'><input type='checkbox' id='checker' />Check/Uncheck All</div>

<form action='index.php' method='post'>
<div style='margin: 10px'>
	<input type='checkbox' name='emotions[]' class='checkboxes' value='Happy' />Happy
	<input type='checkbox' name='emotions[]' class='checkboxes' value='Sad' />Sad
	<input type='checkbox' name='emotions[]' class='checkboxes' value='Excited' />Excited
	<input type='checkbox' name='emotions[]' class='checkboxes' value='Scared' />Scared
</div>
<div style='margin: 10px'>
	<input type='hidden' name='action' value='get_values' />
	<input type='submit' value='Submit Selected' />
</div>
<div style='margin: 10px'>
<?php
	//Defining indexes
	empty($_POST['action']) ? $action = '' : $action = $_POST['action'];
	empty($_POST['emotions']) ? $emotions = '' : $emotions = $_POST['emotions'];

	if( $action == 'get_values'){
		if(!empty($emotions)){ //check if user ticked any checkbox
			foreach($emotions as $keys => $values){
				echo "<div>$values</div>";
			}
		}else{
			echo "Please select emotions.";
		}
	}
?>
</div>
</form>

<script type='text/javascript' src='js/jquery-1.6.1.min.js'></script>
<script type='text/javascript'>
	$(document).ready(function() {
		$( '#checker' ).click(function(){
			$( '.checkboxes' ).attr( 'checked', $( this ).is( ':checked' ) );
		});
	});
</script>

</body>
</html>

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Thank you for learning from our post about: Check or Uncheck Checkboxes with jQuery And Get Selected with PHP.