CreateaFreeWebsite

Check Box Forms
Barbones

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

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)

The HTML code:


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

or

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

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

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:

What are your favorite pies?





 

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

The HTML5 Code:

	
<!DOCTYPE html>
<html>
<head>
<title>Text Selection Box1</title>
<meta  charset="utf-8">
</head>
<body>
<h4>What are your favorite pies?</h4>

<form method="post" action="parse-pies.php">
    <label><input type="checkbox" name="pies[]" value="Apple"> Apple</label><br>
    <label><input type="checkbox" name="pies[]" value="Banana"> Banana</label><br>
    <label><input type="checkbox" name="pies[]" value="Cherry"> Cherry</label><br>
    <label><input type="checkbox" name="pies[]" value="Pizza"> Pizza</label><br>
    <button type="submit">Submit</button>
</form>
</body>
</html>

Advanced Linux Students: Copy the code and save it in your var/www/html folder as form-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.


<?php
// Process form when submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Check if 'pies' checkbox array exists
    $selectedFruits = $_POST['pies'] ?? [];

    // Validate: Ensure it's an array
    if (!is_array($selectedFruits)) {
        $selectedFruits = [];
    }

    // Sanitize each value
    $selectedFruits = array_map(fn($pies) => htmlspecialchars($pies, ENT_QUOTES, 'UTF-8'), $selectedFruits);

    // Output results
    if (count($selectedFruits) > 0) {
        echo "<h3>You selected:</h3><ul>";
        foreach ($selectedFruits as $pies) {
            echo "<li>{$pies}</li>";
        }
        echo "</ul>";
    } else {
        echo "<p>No pies selected.</p>";
    }
}
?>



Advanced Linux Students: Copy the code and save it in your var/www/html folder as parse-pies.php

See: Using the Localhost (Learn to edit and browse forms via the Localhost server)

 

Top