Wednesday, 8 October 2014

Get Multiple Checkbox Values in PHP

<form action="" method="post">
<label class="head">Select Your Hobbies:</label><br/><br/>
<input type="checkbox" name="hobbies[]" value="Playing"><label>Playing</label><br/>
<input type="checkbox" name="hobbies[]" value="Coding"><label>Coding.</label><br/>
<input type="checkbox" name="hobbies[]" value="Reading"><label>Reading</label><br/>
<input type="checkbox" name="hobbies[]" value="Hacking"><label>Hacking</label><br/>
<input type="checkbox" name="hobbies[]" value="Sleeping"><label>Sleeping</label><br/><br/>
<input type="submit" name="submit" Value="Submit"/>

</form>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['hobbies'])) {

//Loop through hobbies array to fetch individual hobby so that we can use them
echo "<h2> You have selected: </h2>";
foreach($_POST['hobbies'] as $hobby) {
echo "<p>".$hobby ."</p>"; //Print all the hobbies

/* Alert hobbies using JS
$show = "<p>".$hobby ."</p>";
echo "<script type='text/javascript'>alert(\"Your Hobbies are: '$show'\");</script>";

*/
}
}
else{
echo "<b>Please Select at least One Hobby.</b>";
}
}
?>

0 comments:

Post a Comment