Alternative ways to set select element's value during validation of a form?
Norm开发者_C百科ally I would do something like this:
<select name="myselect">
<option value="opt1" <?=($_POST['myselect']=="opt1"?"SELECTED":"")?>>Option 1</option>
<option value="opt2" <?=($_POST['myselect']=="opt2"?"SELECTED":"")?>>Option 2</option>
</select>
However this time I've taken a list of all the countries in a select from this website: http://snippets.dzone.com/posts/show/376
To go through each of those and put in the validation will be insane.
There is a php solution in the comments but it seems somewhat inelegant.
Is there an alternative way to do this or something similar? I would prefer not to use javascript, and I'm not sure I want to rely on the browser caching.
Thanks
// I'm using integers as key values in this example. Modify as needed.
$countries = array(
1 => 'Some Country',
// etc...
);
// Sanitize as needed, casting to integer in my example
$selectedCountryCode = isset( $_POST['myselect'] ) ? (int) $_POST['myselect'] : null;
$select = '<select name="myselect">';
foreach( $countries as $countryCode => $countryName )
{
$selected = $selectedCountryCode == $countryCode ? ' selected="selected"' : '';
$select .= '<option value="' . $countryCode .'"' . $selected . '>' . $countryName . '</option>';
}
$select .= '</select>';
echo $select;
You could create select with an array like this:
$options = array('opt1' => 'Option1', 'op2' => 'Option2');
foreach ($options as $o => $v)
{
if ($_POST['myselect'] == $o)
echo '<option value="' . $o . '" selected="selected">' . $v . '</option>';
else
echo '<option value="' . $o . '">' . $v . '</option>';
}
Add countries to value-label
array
Generate options with loop
foreach ($countries as $value => $label) {
$isSelected = $_POST['myselect'] == $value ? ' selected="selected"': '';
echo '<option value="' . $value . '"' . $isSelected . '>' . $label . '</option>';
}
精彩评论