有人可以告诉我更好的做法:
HTML
<select id="customer_country" name="customer_country"
class="validate[required] input_styling"
style="background: #FFFFFF;">
<option value="">Please Select a Country</option>
<option value="Afghanistan" >Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
<option value="American Samoa">American Samoa</option>
<option value="Andorra">Andorra</option>
<option value="Angola">Angola</option>
<option value="Anguilla">Anguilla</option>
<option value="Antarctica">Antarctica</option>
<option value="Antigua and Barbuda">Antigua and Barbuda</option>
<option value="Argentina">Argentina</option>
</select>
鉴于上述<select>
元素,如何将特定选项标记为selected
,具体取决于它是否与从MYSQL语句中获取的变量值匹配,而无需编写以下多次
<option value = "Anguilla" <? if ($variable == "Anguilla") { echo 'selected'; } ?> </option>
<option value = "Antarctica" <? if ($variable == "Antarctica") { echo 'selected'; } ?> </option>
<option value = "Antigua and Barbuda" <? if ($variable == "Antigua and Barbuda") { echo 'selected'; } ?> </option>
<option value = "Argentina" <? if ($variable == "Argentina") { echo 'selected'; } ?> </option>
因此,匹配的option
将被标记为selected
,而无需多次写入上述语句。
有什么建议吗? 谢谢
答案 0 :(得分:2)
你可以:
$selected = "Argentina";
foreach($array as $value){
echo "<option value = '$value'";
if($value == $selected){
echo " selected='selected' ";
}
echo ">$value</option>";
}
答案 1 :(得分:2)
我们有一个函数可以根据数组输入打印<option>
个标签。它看起来像这样。
function print_options(array $options, $selected = null) {
foreach($options as $key=>$value) {
$selected_attr = '';
if ($selected == $key) {
$selected_attr = 'selected="selected"';
}
echo "<option value=\"{$value}\" {$selected_attr}>{$value}</option>";
}
}
然后你就可以这样称呼它。
<select id="customer_country" name="customer_country" ...>
<option value="">Please Select</option>
<?php print_options(['afghanistan' => 'Afghanistan', 'aland_islands' => 'Åland Islands']) ?>
</select>
这个函数本身更聪明,可以处理字符串和东西,但这就是主意。
答案 2 :(得分:0)
我就是这样做的:
$countries = array(
'Anguilla',
'Antarctica',
'Antigua and Barbuda',
'Argentina',
);
foreach ($countries as $country) {
$options[] = '<option value = "' . $country . '"' . ($country === $variable ? ' selected="selected"' : '') . '>' . $country . '</option>';
}
$out = implode("\n", $options);
echo $out;
您可以将其放入函数中或使用内联函数。包含国家/地区的数组也可能用于页面上的其他内容。