Wie ändert man den voreingestellten Wert in DropDownList mit Javascript?Setzen Sie den ausgewählten Standardwert des Dropdown-Menüs dynamisch
Ich bin neu in JavaScript und ich bleibe bei der Änderung standardmäßig ausgewählten Wert in der Dropdown-Liste. Hier möchte ich meinen voreingestellten Wert "111" auf den neuen Wert ändern. Es muss sich ändern, nachdem ich den Text eingegeben habe, zB "abc" in das Modal und wenn ich den "Ok" Knopf gedrückt habe. Nun muss er den voreingestellten ("abc") in der Dropdown Liste anzeigen, die ich aus dem Textfeld bekomme des Modalen. Und auch die alten Werte haben sich in der Liste nicht geändert.
Code Snippet:
<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>
Ich glaube, ich etwas falsch an
option.text = y.value;
x.add(option, option.defaultSelected, x[0]);