0

Possible Duplicate:
append option to select menu?
how do I add an option to a html form dropdown list with javascript

I have a html select element like below

<form>
<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>
</form> 

I would like to add another option value like below using javascript(not jQuery)

<option>Berry</option> 

Can anyone say how could I do that ??

Thanks

4

4 回答 4

3

首先抓住选择使用document.getElementById

var sel = document.getElementById('mySelect');

然后像这样将选项添加到选择的options集合中

sel.options.add(new Option('text', 'val'));

工作示例

于 2012-11-20T05:21:23.703 回答
0
var x=document.getElementById("mySelect");
var option=document.createElement("option");
option.text="Kiwi";
try{
  // for IE earlier than version 8
  x.add(option,x.options[null]);
}
catch (e){
  x.add(option,null);
}
于 2012-11-20T05:26:58.793 回答
0
    <script type="text/javascript">
function fnc()
{
document.getElementById("mySelect").options.add(new Option('berry'));
}
</script>

<form>
<select id="mySelect">
  <option>Apple</option>
  <option>Pear</option>
  <option>Banana</option>
  <option>Orange</option>
</select>
<input type="button" onclick="fnc()" />
</form> 
于 2012-11-20T05:27:14.323 回答
0
//Declare some variables
var ctn = "Berry",
    opt = document.createElement("option");

//Set the text
opt.innerText = ctn;

//Put it in
document.getElementById('mySelect').appendChild(opt);

现场演示:http: //jsfiddle.net/DerekL/BzZXn/

这也适用于所有 HTML 标记。

于 2012-11-20T05:22:22.233 回答