Flo Bayer
Flo Bayer

Reputation: 1260

Adding an option to a select does not work in Internet Explorer

Problem

If you add an option to a select via JavaScript subsequently everything seems to be good.

But if you have a form which is filled via database e.g. and an option from that select is preselected Internet Explorer fails: It's always the next option that is preselected.

All other browsers work fine.

Example

Here is a working example:

var oSelect = document.getElementById('myselect');
var oOption = document.createElement('option');
oOption.text = '- - - my fabulous new option - - -';
oSelect.add(oOption, oSelect[3]);
<select id="myselect">
  <option value="Algeria,DZA">Algeria</option>
  <option value="American Samoa,ASM">American Samoa</option>
  <option value="Andorra,AND">Andorra</option>
  <option selected value="Angola,AGO">Angola</option>
  <option value="Anguilla,AIA">Anguilla</option>
  <option value="Antarctica,ATA">Antarctica</option>
</select>

JSFiddle

And here it's on JSFiddle.

Question

Do you have any idea why IE reacts differently here?

Thanks in advance!

Upvotes: 1

Views: 200

Answers (1)

Jonas M. Schlatter
Jonas M. Schlatter

Reputation: 512

The difficulty is introduced by the insertion of "your fabulous new option". ;)

If you insert it as 5th entry (oSelect[4]) IE keeps html's selected value "Angola,AGO" selected. Yet adding something before this entry messes things up. The problem being that it will select entry [3] without checking if "Angola,AGO" still holds that position.

Edit / Workaround

Selecting via JScript does work with IE, too. Lo, the extra <3 it always needs.

var oSelect = document.getElementById('myselect');
var oOption = document.createElement('option');
oOption.text = '- - - my fabulous new option - - -';
oSelect.add(oOption, oSelect[3]);

// oSelect.value = "Angola,AGO";  <-- changed because of comments
oSelect.value = oSelect.options[oSelect.selectedIndex].value;
<select id="myselect">
  <option value="Algeria,DZA">Algeria</option>
  <option value="American Samoa,ASM">American Samoa</option>
  <option value="Andorra,AND">Andorra</option>
  <option selected value="Angola,AGO">Angola</option>
  <option value="Anguilla,AIA">Anguilla</option>
  <option value="Antarctica,ATA">Antarctica</option>
</select>

Upvotes: 1

Related Questions