2014-07-04 82 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和選項文本是輸入框的值...並希望您能夠理解。