You must set the attribute selected
in the element option
.
See http://reference.sitepoint.com/html/option/selected
<form>
<label for="favoritefood">Favorite food</label>
<select name="favoritefood" id="favoritefood">
<option value="che">Cheese</option>
<option value="egg" selected="selected">Egg</option>
<option value="cab">Cabbage</option>
</select>
</form>
The array $_POST
will either contain the numerical index of the option element, or value
if this attribute is specified. The above example $_POST['favoritefood']
contains an "egg". You can create an assistant that will create option elements for you, for example.
<?php
class HtmlHelper
{
public static function option($value, $label, $selected)
{
$selected = ($value === $selected) ? ' selected="selected"' : '';
return sprintf('<option value="%s"%s>%s</option>%s',
$value, $selected, $label, PHP_EOL);
}
}
echo HtmlHelper::option('che', 'Cheese', $_POST['favoritefood']),
HtmlHelper::option('egg', 'Egg', $_POST['favoritefood']),
HtmlHelper::option('cab', 'Cabbage', $_POST['favoritefood']);
, Selectbox, POST , , . , .
PHP, , javascript, , $_POST, script , . .