reggie
reggie

Reputation: 3674

Selecting correct option with Javascript in Internet Explorer

I have a problem with Internet Explorer not correctly selecting an option when a javascript event is triggered.

I track the events of a marker on a google map. When the marker is moved, I want the right country to be chosen from a select list.

Part of the code that switches the country selection:

<script type="text/javascript">
//...
document.getElementById("id_country").value = country;
//...
</script>

It works just fine in Google Chrome. I know that the country name that is being returned by the map matches the ones in the option field values. In Internet Explorer, nothing happens.

<select id="id_country" name="country">
    <option value="Afghanistan">Afghanistan</option>
    <option value="Aland Islands">Aland Islands</option>
    <!--...-->
</select>

How do I get Internet Explorer to select the correct option (without using jquery)?

Upvotes: 2

Views: 4510

Answers (3)

Steve Brush
Steve Brush

Reputation: 3181

Here's a code sample demonstrating @afshin's answer (thank you!):

function setCountryOption(country) {
  const selectEl = document.getElementById('id_country');
  const options = selectEl.options;

  for (let i = 0, len = options.length; i < len; i++) {
    if (options[i].value == country) {
      options[i].setAttribute('selected', 'selected');
    }
  }
}

Upvotes: 0

cem
cem

Reputation: 1911

selectedIndex property would work but as Afshin said You need to iterate options first.

var elCountry = document.getElementById("id_country");
var options = elCountry.options;
for (var i = 0; i < options.length; i++) {
    if (options[i].value == country) {
        elCountry.selectedIndex = i;
    }
}

Upvotes: 4

afshin
afshin

Reputation: 204

You need to iterate through the options collection of document.getElementById('id_country') and set the matching option's "selected" attribute to the string "selected"

Upvotes: 1

Related Questions