PHP 在编辑模式下显示所选值以下拉
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2171356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP while in edit mode show selected value in to drop down
提问by Bharanikumar
This question was asked already, but my question is very simple.
这个问题已经问过了,但我的问题很简单。
In the my account page, I have the employee country in a dropdown.
在我的帐户页面中,我在下拉菜单中有员工所在的国家/地区。
How to select a value in the combo, when in edit mode?
在编辑模式下,如何在组合中选择一个值?
回答by Matteo Riva
Let's assume you have the user's country in $user_countryand the list of all countries in $all_countriesarray:
假设您有用户所在的国家/地区$user_country以及$all_countries数组中所有国家/地区的列表:
<select id="country">
<?php
foreach ( $all_countries as $country ):
$selected = "";
if ( $country == $user_country )
$selected = "selected";
?>
<option value="<?php echo $country; ?>"
selected="<?php echo $selected; ?>">
<?php echo $country; ?>
</option>
<?php
endforeach; ?>
</select>
should work.
应该管用。
回答by Bharanikumar
function p_edit_combo($cCurstatus,$h_code_default,$h_name=NULL){
<select name="<?php echo $cCurstatus;?>" id="<?php echo $cCurstatus;?>" class="main_form_select">
<option value="">Select</option>
<?php
$sql_h = "SELECT h_code,h_name FROM med_hl WHERE status = 1";
$sql_h_result = mysql_query($sql_h);
while($row=mysql_fetch_array($sql_h_result)){
$h_code = $row['h_code'];
$h_name = $row['h_name'];
?>
<option <?php if($h_code_default==$h_code){ ?> selected="selected" <?php }?> value='<?php echo $h_code; ?>' >
<?php echo $h_code."|".$h_name; ?>
</option>
<?php } ?>
</select>
<?php
}
回答by nortron
An optiontag will be the default for a selectlist when the selectedattribute is set. In the following code option 2 will show up as the current selected option when the page loads:
一个option标签将是一个默认的select列表,当selected属性设置。在以下代码中,选项 2 将在页面加载时显示为当前选定的选项:
<select>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
</select>
To achieve this in your PHP code conditionally display the selected attribute on your options against what the current value is:
要在您的 PHP 代码中实现这一点,有条件地在您的选项上显示 selected 属性,而不是当前值:
<option value="1"<?php if($user['country'] == '1') { ?> selected="selected"<?php } ?>>1</option>
<option value="2"<?php if($user['country'] == '2') { ?> selected="selected"<?php } ?>>2</option>
<option value="3"<?php if($user['country'] == '3') { ?> selected="selected"<?php } ?>>3</option>

![PHP | 通过 $_POST[] 获取输入名称](/res/img/loading.gif)