[英]how do I add an option to a html form dropdown list with javascript
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>
You need to actually add the option object to the dom. 您需要实际将选项对象添加到dom。 I have linked to a fiddle with your example working: http://jsfiddle.net/DS8TG/
我已经链接到你的例子工作的小提琴: 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');
}
try out this 试试这个
var element = document.getElementById('list');
element.options[element.length]
= new Option('yourText', 'yourValue');
var select = document.getElelmentById('test');
var option = document.createElement('option');
option.value = 'value';
select.appendChild(option)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.