2014-07-04 86 views
0

我知道改变一个输入文本的值。如何将值添加到空白SELECT?

<script> 
    document.write('<input type="text" id="1" value="Hello">'); 
    document.getElementById('1').value = ("Good bye"); 
</script> 

如何使用此方法将值添加到空的SELECT?

<script> 
    document.write('<select><option id="2"></option><option id="3"></option></select>'); 
    document.getElementById ........; 
</script> 

我想让我的空SELECT成为一个带有两个选项的SELECT:“Hello”和“Good Bye。”。

+0

你已经有了select元素吗?那是你在说什么? –

回答

1

为什么不写:

document.write('<select><option id="2">Hello</option><option id="3">Good bye</option></select>'); 

或者,如果你想添加一个编程:

document.write('<select id="s"></select>'); 
var s = document.getElementById("s"); 

var option = document.createElement("option"); 
option.text = "Hello"; 
s.add(option); 

var option = document.createElement("option"); 
option.text = "Good bye"; 
s.add(option); 
+0

我认为最好使用'appendChild'而不是'add' – Apolo

-1

您可以使用jQuery

$(document).ready(function() { 
$("select").append('<option id="3" value="somevalue">Some text</option>"'); 
}); 
1

这是很简单很容易做到这一点。 ...

<script> 
    var add = function(){ 
    var sel = document.getElementById("sel"); 
    var in1 = document.getElementById("in").value; 

    var opt = document.createElement("option"); 
    opt.innerHTML = in1; 

    sel.appendChild(opt); 
} 
</script> 
<select id="sel"> 

</select> 
<input id="in" type="text" /> 
<button onclick="add();">add</button> 

这里是演示:CLICK 另一exanple如何使用innerHTML做这件事情是在这里:jsfiddle

这是通过一个元素,你使用的JavaScript知道option,然后它是在元素追加完成select和选项文本是输入框的值...并希望您能够理解。