I am trying to make default selection of a dropdown selection to be blank.
If I generate a select dropdown with HTML, it works. However when I generate the same dropdown with javascript, it does not work.
Please see http://jsfiddle.net/m2HSb/
<select id="myDropdown">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<div id="yo"></div>
document.getElementById("myDropdown").selectedIndex = -1
var my_select = document.createElement("select")
for ( var i = 0 ; i < 3 ; i++ ) {
my_select.options[i] = new Option(i,i)
}
my_select.selectedIndex = -1
document.getElementById("yo").appendChild(my_select)
Note that the first dropdown is blank, and the second is not.
Apparently you can't set the selectedIndex
of a select
element that hasn't been inserted into the DOM yet.
If you move my_select.selectedIndex = -1
after the append
then it works fine.
var my_select = document.createElement("select");
for ( var i = 0 ; i < 3 ; i++ ) {
my_select.options[i] = new Option(i,i);
}
document.getElementById("yo").appendChild(my_select);
my_select.selectedIndex = -1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.