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="">

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

Attributes

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

 

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
Hiking
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>
<html>
<head>
<title>Text Checkbox</title>
<meta charset="utf-8">
</head>
<body>
<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>
</form>
</body>
</html>

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>
<html>
<head>
<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
}
</style>
</head>
<body>
<?
$passtime=$_POST['passtime'];
print "<div>";
print "<h1>Your Choices</h1>";
print "<p>";
foreach ($passtime as $value){
print "$value<br>";
}
print "</p></div>";
?>
</body>
</html>

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