javascript 自动选择下拉值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5607338/
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
Auto select value of dropdown
提问by WebDDelhi
How can I auto select a field in dropdown.
如何在下拉列表中自动选择一个字段。
Say if someone goes to www.xyx/form/?abc
Some value gets selected in the dropdown,
假设有人去www.xyx/form/?abc
某些值在下拉列表中被选中,
Or if someone goes to www.xyx/form/?def
Some other value gets selected in the dropdown.
或者,如果有人去www.xyx/form/?def
下拉菜单中选择了其他一些值。
I am comfortable with JS and php.
我对 JS 和 php 很满意。
回答by Adam Kiss
assuming example.com/?sel=xxx
假设 example.com/?sel=xxx
<?php
$sel = $_GET['sel'];
?>
<select ...>
<option val="xxx" <?php if($sel==='xxx') echo 'selected="selected"';?>>Option XXX</option>
<option val="yyy" <?php if($sel==='yyy') echo 'selected="selected"';?>>Option YYY</option>
</select>
No Javascript needed.
不需要Javascript。
回答by Jared Farrish
PHP
PHP
<select name="select">
<option value="abc"<?php ($_GET['select'] == 'abc'? echo 'selected="selected"' : ''); ?>>ABC</option>
<option value="def"<?php ($_GET['select'] == 'def'? echo 'selected="selected"' : ''); ?>>DEF</option>
</select>
回答by Alan Whitelaw
<option value="abc" <?php echo isset($_GET['abc']) ? 'selected="selected"' : ''; ?>>abc</option>
回答by Raheel Hasan
hmmm, so what will you do when you have 100s of items in the Options list? The other ideas wont look so great then.
嗯,那么当您的选项列表中有 100 个项目时,您会怎么做?其他想法不会看起来那么好。
Then you will need to just simply write 1 line of code at the end of select tag:
然后你只需要在 select 标签的末尾简单地写 1 行代码:
<?php if(isset($_POST['env_foil_color'])) echo "<script>document.getElementById('env_foil_color').value='{$_POST['env_foil_color']}';</script>"; ?>
where, 'env_foil_color' is the select tag's ID and Name both
其中,'env_foil_color' 是选择标签的 ID 和名称