1. Check or Uncheck All Checkboxes in a form (using jQuery).
2. Get the selected checkboxes values when the form is submitted (using PHP).
Just like select/unselect all |
<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='#' method='post'>
<div style='margin: 10px'>
//name should be like in array format: emotions[]
<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'>
//the action when the from is submitted: get_values
<input type='hidden' name='action' value='get_values' />
<input type='submit' value='Submit Selected' />
</div>
<div style='margin: 10px'>
<?php
//Defining indexes/posted values
empty($_POST['action']) ? $action = '' : $action = $_POST['action'];
empty($_POST['emotions']) ? $emotions = '' : $emotions = $_POST['emotions'];
if( $action == 'get_values'){
//check if user ticked any checkbox
if(!empty($emotions)){
//loop to display values
foreach($emotions as $keys => $values){
echo "<div>$values</div>";
}
}else{
//message when there's no selected checkbox
echo "Please select emotions.";
}
}
?>
</div>
//jQuery library used: jquery-1.6.1.min.js
<script type='text/javascript' src='js/jquery-1.6.1.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
//check/uncheck script
$( '#checker' ).click(function(){
$( '.checkboxes' ).attr( 'checked', $( this ).is( ':checked' ) );
});
});
</script>
</body>
</html>
The Code of a Ninja Resources
For FREE programming tutorials, click the red button below and subscribe! :)
website