PHP HTML Checkbox
From w3cyberlearnings
Contents |
PHP works with HTML Checkbox
Checkbox permits multiple select option at a time.
Syntax single checkbox
<input type="checkbox" name="book" value="java"/>Java<br />
Syntax single checkbox with default check
<input type="checkbox" name="book" value="java" checked="checked"/>Java<br />
Syntax multiple checkbox
- Check out the example for understand how the multiple check work.
<input type="checkbox" name="book[]" value="java1"/>Java<br /> <input type="checkbox" name="book[]" value="java2"/>Java<br /> <input type="checkbox" name="book[]" value="java3"/>Java<br /> <input type="checkbox" name="book[]" value="java4" checked="checked">Java<br />
Example 1
<?php if ($_POST) { echo '<pre>'; print_r($_POST); echo '</pre>'; } ?> <html> <head> <title>Checkbox</title> </head> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <i>Option</i><br/> <input type="checkbox" name="book" value="java" checked="checked">Java<br /> <input type="checkbox" name="people" value="people">People<br /> <input type="checkbox" name="forest" value="forest">Forest<br /> <input type="checkbox" name="small" value="Tree">Tree<br /> <br/> <i>School</i><br/> <input type="checkbox" name="school[]" value="gsu">GSU<br /> <input type="checkbox" name="school[]" value="lsu" checked="checked">LSU<br /> <input type="checkbox" name="school[]" value="mit">MIT <br/> <input type="submit" name="submit"/> </form> </body> </html>
Output
Example 2
<?php $str = ""; if ($_POST) { foreach ($_POST as $name => $value) { if ($name == "book" && $value != "") { $str.= "<li> The book name {$value} is great!</li>"; } else if ($name == "people" && $value != "") { $str .="<li> Please, take care our people </li>"; } else if ($name == "forest" && $value != "") { $str .= "<li> Please, take care our tree and planet!</li>"; } else if ($name == "small" && $value != "") { $str .="<li> Those small trees are not that simple to take care.</li>"; } else if ($name == "school" && count($value) > 0) { $str .= '<li> school name: ' . implode(',', $value) . '</li>'; } } if ($str != "") { echo "<ul>" . $str . "</ul>"; } else { echo "Please try again!"; } } ?> <html> <head> <title>Checkbox</title> </head> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <i>Option</i><br/> <input type="checkbox" name="book" value="java" checked="checked">Java<br /> <input type="checkbox" name="people" value="people">People<br /> <input type="checkbox" name="forest" value="forest">Forest<br /> <input type="checkbox" name="small" value="Tree">Tree<br /> <br/> <i>School</i><br/> <input type="checkbox" name="school[]" value="gsu">GSU<br /> <input type="checkbox" name="school[]" value="lsu" checked="checked">LSU<br /> <input type="checkbox" name="school[]" value="mit">MIT <br/> <input type="submit" name="submit"/> </form> </body> </html>
Output
Related Links
- HTML Textbox
- HTML Checkbox
- HTML Radio