Reputation: 71
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.
Upvotes: 0
Views: 1602
Reputation: 23250
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;
Upvotes: 2