0

Plain and simple: Why does adding the option to the select element alters its selectedIndex and is there a way to either:

  1. Prevent this behavior
  2. Detect it

var list = document.getElementById("list");
list.selectedIndex = -1;
document.write("</br>Selected index: " + list.selectedIndex);
$(list).append('<option value="foo">foo</option>');
document.write("</br>Selected index: " + list.selectedIndex);
list.selectedIndex = -1;
document.write("</br>Selected index: " + list.selectedIndex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="list">      
</select>
Oliver Weichhold
  • 10,259
  • 5
  • 45
  • 87

2 Answers2

0

selectedIndex

By assigning -1 to this property, all items will be deselected. Returns -1 if no items are selected.

For a normal select, it's only possible to have no items selected when there are no items to select. As soon as you add at least one item, a selection must exist.

If you have a select multiple, however, the value will be preserved.

var list = document.getElementById("list");

document.write("</br>Selected index: " + list.selectedIndex);
$(list).append('<option value="foo">foo</option>');
$(list).append('<option value="foo">foo</option>');
$(list).append('<option value="foo">foo</option>');
document.write("</br>Selected index: " + list.selectedIndex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="list" multiple>      
</select>
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • What if only one option is there ? – Rayon Oct 27 '15 at 20:11
  • Is where? `select` or `select multiple`? – Blazemonger Oct 27 '15 at 20:12
  • 1
    As I said: in a normal `select` dropdown, exactly one option is displayed/selected at all times -- except when there are no options at all. – Blazemonger Oct 27 '15 at 20:14
  • @Blazemonger But then again, why is it possible to clear the selection after adding an option by setting the selectedIndex to -1? I've updated the snippet. – Oliver Weichhold Oct 27 '15 at 20:23
  • Not sure, to be honest. All I can say is, you probably shouldn't do that anyway, since it's only possible in JS and not through normal user interaction. Use `select multiple`, radio buttons, or `` if you need to be able to have no option selected. – Blazemonger Oct 27 '15 at 20:33
0

You can manually reset it after adding an option, basically add list.selectedIndex = -1; after $(list).append('<option value="foo">foo</option>');

imnancysun
  • 612
  • 8
  • 14