This tutorial will show you how to add select boxes and multi-select boxes to a form, how to retrieve the input data from them, how to validate the data, and how to take different actions depending on the input.
Select box
Let’s look at a new input: a “select” box, also known as a “drop-down” or “pull-down” box. A select box contains one or more “options”. Each option has a “value”, just like other inputs, and also a string of text between the option tags. This means when a user selects “Male”, the “formGender” value when accessed by PHP will be “M”.
<p>
Gender :
<select name="formGender">
<option value="">Select</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</p>
The selected value from this input was can be read with the standard $_POST array just like a text input and validated to make sure the user selected Male or Female.
<?php
if(isset($_POST['formSubmit']) )
{
$varMovie = $_POST['formMovie'];
$varName = $_POST['formName'];
$varGender = $_POST['formGender'];
$errorMessage = "";
}
?>
It’s always a good idea to have a “blank” option as the first option in your select box. It forces the user to make a conscious selection from the box and avoids a situation where the user might skip over the box without meaning to. Of course, this requires validation.
<?php
if(!isset($_POST['formGender']))
{
$errorMessage .= "<li>You forgot to select your Gender!</li>";
}
?>
Handling drop-down list in a PHP form
No comments:
Post a Comment