Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Select Index value not changing

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>
like image 746
keith Spiteri Avatar asked Oct 27 '25 03:10

keith Spiteri


1 Answers

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;
like image 82
Greg Burghardt Avatar answered Oct 28 '25 19:10

Greg Burghardt