答案 0 :(得分:1)
在select标签上设置预选选项需要您在所选选项上放置一个选定的属性。
<select style="margin-left:25px;">
<?php
$options = array(array("null"," "),array("single","Single"),array("in_a_relationship","In a relationship"),array("engaged","Engaged"),array("married","Married"),array("open_rel","In an open relationship"),array("divorced","Divorced"));
foreach ($option in $options){
if ($option[0] == $row3['status']){
$selected = 'selected ';
}
else{
$selected = '';
}
echo '<option '.$selected.'value="'.htmlspecialchars($option[0]).'">'.htmlspecialchars($option[1]).'</option>';
}
?>
</select>
答案 1 :(得分:1)
以下是在HTML中选择Single
选项的方法:
<select style="margin-left:25px;">
<option value="null"> </option>
<option value="single" selected>Single</option>
<option value="in_a_relationship">In a relationship</option>
<option value="engaged">Engaged</option>
<option value="married">Married</option>
<option value="open_rel">In an open relationship</option>
<option value="divorced">Divorced</option>
</select>
那么,如何在PHP中设置它?!
好吧,你可以像这样生成你的<select>
元素:
<?php
$options = [
'null' => ' ',
'single' => Single',
'in_a_relationship' => 'In a relationship',
'engaged' => 'Engaged',
'married' => 'Married',
'open_rel' => 'In an open relationship',
'divorced' => 'Divorced'
];
?>
<select style="margin-left:25px;"><?php
foreach($options as $key => $value) {
echo '<option value="' . $key . '"';
if ($key === $row3['status']){
echo ' selected';
}
echo '>' . $value . '</option>';
}
?></select>
答案 2 :(得分:0)
Musa的解决方案没关系,但是如果你不想改变你的PHP太多 你可以使用Javascript完成任务。
使用jQuery或纯Javascript
function selector(id, value){
select = document.getElementById(id);
for(i=0;i<select.options.length;i++){
if(select.options[i].value == value){
select.selectedIndex = i;
}
}
}
//Pure Javascript
selector("status", "engaged")
//With jQuery
jQuery('#status').val('married');
选中此Snippet