问问题
1812 次
4 回答
1
您需要检查要选择的选项,然后打印选定的标签:
$civil_status = $row[8]; //value from selecting the database
<tr>
<td>Civil Status:</td>
<td><select name="civil_status" >
<option value="single" <?php $civil_status=="single" ? print "selected" : ""; ?> >Single</option>
<option value="married" <?php $civil_status=="married" ? print "selected" : ""; ?> >Married</option>
</select></td>
</tr>
于 2013-11-04T13:43:48.167 回答
1
您需要selected="selected"
在选项标签中设置。像这样尝试
$civil_status = $row[8]; //value from selecting the database
<tr>
<td>Civil Status:</td>
<td><select name="civil_status">
<option value="single" <?php if($civil_status == 'Single') echo 'selected="selected"';?>>Single</option>
<option value="married" <?php if($civil_status == 'Married') echo 'selected="selected"';?>>Married</option>
</select></td>
</tr>
于 2013-11-04T13:39:52.237 回答
1
您可以通过快速而肮脏的方式来做到这一点:
<tr>
<td>Civil Status:</td>
<td>
<select name="civil_status">
<option value="single"<?php print($civil_status == "single" ? ' selected="selected"' : ""); ?>>Single</option>
<option value="married"<?php print($civil_status == "married" ? ' selected="selected"' : ""); ?>>Married</option>
</select>
</td>
</tr>
或者您可以编写一个辅助函数来生成整个<option>
集合:
function select_options($options, $selected)
{
$result = "";
foreach($options as $value => $label)
{
$result .= '<option value="' .
htmlentities($value, ENT_QUOTES, "UTF-8") . '"' .
($selected == $value ? ' selected="selected"' : "") . '>' .
htmlentities($label, ENT_QUOTES, "UTF-8") . '</option>';
}
return $result;
}
select_options有两个参数。第一个是关联数组 ( key => value, ...
),其中数组键是value
各个<option>
标签的参数值,数组值包含要为每个键显示的标签。
第二个参数指定value
要在选择框中选择的项目。
然后该函数遍历数组并为每个项目提取value
和。label
然后它将相应的<option>
标签附加到结果字符串中。它还在参数上调用htmlentities以避免跨站点脚本漏洞。
然后是踢球者:如果它在选择框 ( ) 中看到应该选择的项目,它会自动将参数$selected == $value
附加到标签并因此选择该元素。selected="selected"
<option>
要使用该功能,请执行以下操作:
<tr>
<td>Civil Status:</td>
<td>
<select name="civil_status">
<?php
print(select_options(array(
"single" => "Single",
"married" => "Married"
), $civil_status));
?>
</select>
</td>
</tr>
在您需要创建选择菜单的任何地方都更加清洁和可重复使用。
于 2013-11-04T13:47:30.647 回答
0
你可以试试这个,
<?php
$civil_status = $row[8]; //$civil_status ='married';
$civil_statuses = array('single', 'married');
?>
<select name="civil_status">
<?php foreach($civil_statuses as $status){ ?>
<option value="<?php echo $status;?>" <?php echo if($civil_status==$status){ echo 'selected';} ?> ><?php echo ucfirst($status);?></option>
<?php }?>
</select>
于 2013-11-04T13:43:59.707 回答