php HTML选择选项设置选定的默认回声获取值php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26644349/
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
HTML select option set selected default echo get value php
提问by Grupo456436657
I have a simple HTML form with a simple select like this
我有一个简单的 HTML 表单,像这样一个简单的选择
<select name="myselect" selected="<?php echo $_GET['brand'];?>">
<option value="" <?php if($brand== "") echo "selected"; ?>>all brands</option>
<option value="samsung" <?php if($brand== "samsung") echo "selected"; ?>>Samsung</option>
<option value="motorola" <?php if($brand== "motorola") echo "selected"; ?>>Motorola</option>
</select>
What I am trying to do is because its a search filtering results form if the user choose Samsung as default brand to search next page with filteres search results will the select option default selected Samsung and no other. If user select to search Motorola then the selected option default will be Motorola.
我想要做的是因为它是一个搜索过滤结果表单,如果用户选择三星作为默认品牌来搜索带有过滤器搜索结果的下一页,则选择选项将默认选择三星而不是其他。如果用户选择搜索摩托罗拉,则选择的选项默认为摩托罗拉。
How do I fix this?
我该如何解决?
回答by Sudhir Bastakoti
selectedis attribute of option
not select
, so remove it from select
tag, change to:
selected是option
not 的属性select
,因此将其从select
标签中删除,更改为:
<?php $brand = trim( strtolower($_GET['brand']) ); ?>
<select name="myselect">
<option value="" <?php if($brand== "") echo "selected"; ?>>all brands</option>
<option value="samsung" <?php if($brand== "samsung") echo "selected"; ?>>Samsung</option>
<option value="motorola" <?php if($brand== "motorola") echo "selected"; ?>>Motorola</option>
</select>
回答by Muhammad Fahad
This is Simple Example of selected=selected by using foreach loop and ternary operators in php... use can easily understand and customize that code...
这是在 php 中使用 foreach 循环和三元运算符的 selected=selected 的简单示例...使用可以轻松理解和自定义该代码...
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
<option value="<?php echo $key;?>" <?php echo ($key == '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
回答by Mishen Daishika
<?php $selected_brand = $_GET['brand'];
$temp_str = '';
$temp_str .= '<select name="myselect">';
$brands_array = array("all" => "all brands", "samsung" => "Samsung", "motorola" => "Motorola");
foreach ($brands_array as $key => $value) {
if($key == $selected_brand){
// For selected option.
$temp_str .= '<option value="'.$key.'" selected>'.$value.'</option>';
} else {
$temp_str .= '<option value="'.$key.'">'.$value.'</option>';
}
}
$temp_str .= '</select>';
echo $temp_str; // Select box.
?>