|
Pre-selecting and re-selecting options in HTML select boxesPosted: May 10, 2007 Last modified: Apr 27, 2018The 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 <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 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 <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>
|