Javascript 如何使用javascript向html表单下拉列表添加选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10992261/
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
how do I add an option to a html form dropdown list with javascript
提问by StealingMana
I want this script to add an option to the list.
我希望此脚本向列表中添加一个选项。
When you open the list I want the options to be test
and hello
当您打开列表时,我希望选项是test
和hello
What am I doing wrong?
我究竟做错了什么?
<SCRIPT>
function runList(){
document.getElementById('list').value = "<option>hello</option>";
}
</SCRIPT>
<FORM NAME="myform" ACTION="" METHOD="GET">
Your Options:
<INPUT TYPE="button" NAME="button" VALUE="Click" onClick="runList()"/>
<SELECT NAME="list" ID="list">
<OPTION>test</OPTION>
</SELECT>
回答by Jeff Beck
You need to actually add the option object to the dom. I have linked to a fiddle with your example working: http://jsfiddle.net/DS8TG/
您需要将选项对象实际添加到 dom 中。我已链接到您的示例工作的小提琴:http: //jsfiddle.net/DS8TG/
Change runList to the following:
将 runList 更改为以下内容:
function runList(){
var select = document.getElementById('list');
select.options[select.options.length] = new Option('Hello', 'Hello');
}?
回答by Pranay Rana
try out this
试试这个
var element = document.getElementById('list');
element.options[element.length]
= new Option('yourText', 'yourValue');
回答by jordancpaul
var select = document.getElelmentById('test');
var option = document.createElement('option');
option.value = 'value';
select.appendChild(option)