Pre-selecting and re-selecting options in HTML select boxes

The <select> tag is used to display a drop-down box of options in an HTML page. The individual options are created with the <option> tag, one for each option. By default, the first option is selected, but this can be changed with the selected attribute.

The code below demonstrates how to select the second of three options:

<select name="year"> <option value="2005">2005</option> <option value="2006" selected="selected">2006</option> <option value="2007">2007</option> </select>

You can "hard-code" which option to select by setting the selected attribute directly as in the example above. But very often you'll be looping over a (possibly large) set of values, displaying an option for each, and you will have to use some conditional logic to select one. In PHP, you might do something like this:

<select name="year"> <?php for ($year = 2000; $year <= 2007; $year++) { print "<option value=\"$year\"" . ($year == 2006 ? ' selected="selected"' : '') . ">$year</option>\n"; } ?> </select>

The code above makes use of the ternary operator, but the same effect could be achieved by breaking up the print statement in the middle and using an if statement to decide whether to select the current option.

Very often, the value to be selected will be based on some user input. A common case is when a user submits a form that fails a validation test, and the form is redisplayed with the previously selected values in drop-downs re-selected. The code for this could look like the following (which makes use of an if statement instead of the ternary operator):

<select name="year"> <?php for ($year = 2000; $year <= 2007; $year++) { print "<option value=\"$year\""; if ($year == $_POST['year']) print ' selected="selected"'; print ">$year</option>\n"; } ?> </select>