如何使用javascript向html表单下拉列表添加选项

时间:2022-10-31 22:47:32

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>

3 个解决方案

#1


7  

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');
}​

#2


5  

try out this

尝试这个

var element = document.getElementById('list');
element.options[element.length] 
   = new Option('yourText', 'yourValue');

#3


0  

var select = document.getElelmentById('test');
var option = document.createElement('option');
option.value = 'value';
select.appendChild(option)

#1


7  

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');
}​

#2


5  

try out this

尝试这个

var element = document.getElementById('list');
element.options[element.length] 
   = new Option('yourText', 'yourValue');

#3


0  

var select = document.getElelmentById('test');
var option = document.createElement('option');
option.value = 'value';
select.appendChild(option)