Forms and Selection Boxes
Barebones
Selection boxes add a little elegance to the structure of a form.
They simply allow a user to make single or multiple selections from a predefined list.
The HTML Code: Select <select></select>
Attributes
- name (required) supplies the name for the name/value pair.
- size determines the number of options to be displayed at one time. Default=1.
- multiple allows mutiple selections. (Control Key depressed)
Option <option></option>
Note:Include Closing option tag for W3C compliance.
Attributes
- value (Use value attribute as shown for Xhtml compliance.)
A simple selection form(single choice):
A simple selection form (multiple choices):
The HTML5 Form Code (Multiple choices)
For Single Choice: omit size and multiple attributes
<!DOCTYPE html>
<html>
<head>
<title>Text Selection Box1</title>
<meta charset="utf-8">
<style>
select {
background-color: transparent;
border: solid 1px;
padding: 4px;
margin: 0;
width: 25dvw;
font-family: inherit;
font-size: inherit;
cursor: inherit;
line-height: inherit;
}
</style>
</head>
<body>
<form method="post" action="parse-selection.php">
<label for"states">What states have you visited?</label>
<select id="states" name="state[]" size="6" multiple>
<option value="Alabama">Alabama</option>
<option value="Arkansas">Arkansas</option>
<option value="Colorado">Colorado</option>
<option value="Kentucky">Kentucky</option>
<option value="Tennessee">Tennessee</option>
<option value="Washington">Washington</option>
<option value="None of these states">None of the above.</option>
</select>
<br>
<input type="submit"></p>
</form>
</body>
</html>
Note: For people who don't know how to make multiple selections using a selection box.
Include the instruction for holding down the Control Key on your form.
Copy and save as form-selection.html
PHP Script
<?php
// Process form when submitted
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Check if 'state' selection array exists
$selectedState = $_POST['state'] ?? [];
// Validate: Ensure it's an array
if (!is_array($selectedState)) {
$selectedState = [];
}
// Sanitize each value
$selectedState = array_map(fn($state) => htmlspecialchars($state, ENT_QUOTES, 'UTF-8'), $selectedState);
// Output results
if (count($selectedState) > 0) {
echo "<h3>You visited:</h3><ul>";
foreach ($selectedState as $state) {
echo "<li>{$state}</li>";
}
echo "</ul>";
} else {
echo "<p>No state selected.</p>";
}
}
?>
Copy and save as parse-selection.php
See: Using the Localhost (Learn to edit and browse forms via the Localhost server)