javascript动态设置下拉列表的选定默认值
如何使用Javascript更改DropDownList中的默认选定值
我是JavaScript新手,我一直在修改下拉列表中的默认选定值。 在这里,我想将默认选择值“111”更改为新值。在我将文本(例如“abc”)输入模式后,当我点击“Ok”按钮时,它必须更改。现在,它必须在下拉列表中显示默认选择(“abc”),我从模式的文本框中获得该下拉列表。而且列表中的旧值也没有更改
代码段:
<form>
<select id="myList">
<option>111</option>
<option>222</option>
<option>333</option>
</select> <br>
<br>
</form>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<input type="text" id="addtext" size="50" /><br>
Write & add text in the Dropdown list..</text>
<br><br>
<button id="okBtn">OK</button>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the button that add text in the dropdown
var btn1 = document.getElementById("okBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
btn1.onclick = function(){
//var element = document.getElementById('addtext');
var y = document.getElementById("addtext");
var x = document.getElementById("myList");
var option = document.createElement("option");
option.text = y.value;
x.add(option, option.defaultSelected, x[0] );
modal.style.display = "none";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
我想我当时做错了什么
option.text = y.value;
x.add(option, option.defaultSelected, x[0] );
# 1 楼答案
可以使用^{} 属性设置所选选项的索引
如果将其设置为^{,它将选择第一个选项
可以使用^{} 将
option
添加到select
。正确的语法是(来自文档):你使用了三个参数,而不是两个
因此,一种可能的方法是:
工作演示:https://jsfiddle.net/mrlew/w1zqL0h9/
如前所述,如果将
null
作为第二个参数传递,它将把option
附加到末尾。您可以选择将length-1
传递给selectedIndex