[英]Selecting a value in a select box after the value has been added dynamically
在輸入到文本框中並單擊添加按鈕的值后,如何在選擇框中(下拉列表)選擇新添加的值?
<html>
<head>
<script>
function addref(value) {
var x = document.getElementById("thebox");
var option = document.createElement("option");
option.text = value
x.add(option,x.options[null])
}
</script>
</head>
<body>
<form>
<select id="thebox">
</select>
</form>
<br>
<input type="text" id="theinput"/>
<input type="button" value="Add" name="B1" onclick="addref(document.getElementById('theinput').value)"/>
</body>
</html>
嘗試這個:
x.selectedIndex = x.options.length - 1;
之后,您可以使用
var val = x.value;
要么
var val = x[x.selectedIndex].value;
另外,代替x.add(option,x.options[null])
而只需使用x.add(option)
。 這將在option
末尾添加新創建的options
。 第二個參數應為整數,它表示要在其中添加新選項的索引位置。
要獲得選定的值,請使用以下命令:
var e = document.getElementById("thebox");
var theValue = e.options[e.selectedIndex].value;
要獲取所選文本,請使用以下命令:
var e = document.getElementById("thebox");
var theText = e.options[e.selectedIndex].text;
是否動態添加無關緊要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.