Using Check boxes in Forms

Check boxes allow your user to make single or multiple selections from a list.

The HTML code:

Label <input type="checkbox" name="" value="">

<input type="checkbox" name="" value=""> Label


Usually refers to the name of the variable where the value entered on the form is to be stored.
Refers to the information or data entered or selected on the form.
Displays a check mark in the desired input box. (See Code Example)



Red <input type="checkbox" name="color" value="red">
Green <input type="checkbox" name="color" value="green">
Blue <input type="checkbox" name="color" value="blue">

When using check boxes the name attribute must be the same for each check box.

In the example above, multiple check boxes would each share the name color.

In the example above multiple check boxes would include a different color in each value attribute.

The Label preceding or following the check box would match the value.


Now let's build a simple form:

Check Your Favorite Pass Times:
Watching TV
Surfing the net.
Building Web Pages.
Reading a book.
Playing Games.

Note: Try this form. Execution is via PHP. (Script below)

The HTML5 Code:
<!DOCTYPE html>
<title>Text Checkbox</title>
<meta charset="utf-8">
<form method="post" action="parse-checkbox.php">
<p><b>Check Your Favorite Pass Times:</b><br/>
<input type="checkbox" name="passtime[]" value="Watching TV">Watching TV<br/>
<input type="checkbox" name="passtime[]" value="Hiking">Hiking<br/>
<input type="checkbox" name="passtime[]" value="Surfing the Net">Surfing the net.<br/>
<input type="checkbox" name="passtime[]" value="Building Web Pages" checked>Building Web  Pages.<br/>
<input type="checkbox" name="passtime[]" value="Reading a Book">Reading a book.<br/>
<input type="checkbox" name="passtime[]" value="Playing Games">Playing Games.</p>
<p><input type="submit" value="Submit"></p>

Advanced Students: Copy the code and save it in your Apache/htdocs folder ast test-checkbox.html


Execute Form With PHP

PHP scripts don't have to be in a special folder. They can be placed in the same directory or folder with your form.

Here's the simple PHP script that processes the checkbox form above.

<!DOCTYPE html>
<title>Parse Checkbox</title>
<meta charset="utf-8">
<style type="text/css">
body {
font-family: arial, tahoma,serif

div {
display: block;
width: 30%;
margin: 0 auto
print "<div>";
print "<h1>Your Choices</h1>";
print "<p>";
foreach ($passtime as $value){
print "$value<br>";
print "</p></div>";

Note: We did add some basic style settings just for reference.

Advanced Students: Copy the code and save it in your Apache/htdocs folder as parse-checkbox.php