I have the following html code, and I am trying to set the value of option by selectedIndex. The problem is that the option is still displaying the old value whereas if I do an alert on what was selected it gives me the correct answer.
What am I missing?
<select name="select-choice-1" id="select-choice-1">
<option value="none">Choose One</option>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">d</option>
</select>
<script>
var HomeLocation = 1;
document.getElementById("select-choice-1").selectedIndex = HomeLocation;
alert(document.getElementById("select-choice-1").selectedIndex); // shows 1
</script>
I've had inconsistent behavior with browsers. I usually have to set the selectedIndex and set the selected property of the <option>:
var select = document.getElementById("select-choice-1");
select.selectedIndex = 1;
select.options[1].selected = true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With