I have come across a situation where individually, these lines of code work, but in the structure I've put them in they do not. At least, not in IE 11.
If you run this code, the JS reorders the options within the select box according to alphabetical order and then selects the top item. In Chrome and Firefox this works.
In IE v11, the elements get reordered, but the top item ('five') does not become selected. Even weirder, is that if you run the final line in the IE console, it does, in fact, select the top item. So, the issue isn't that IE doesn't understand the syntax. So, what is it?
(I believe this was working as expected in prior versions of IE, but I'm not sure.)
$('#it option').sort(function(a,b){
return ( $(a).text() > $(b).text() ) ? 1 : -1;
}).appendTo( $('#it') );
$('#it option')[0].selected = 'selected';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="it">
<option val="0">zero</option>
<option val="1">one</option>
<option val="2">two</option>
<option val="3">three</option>
<option val="4">four</option>
<option val="5">five</option>
<option val="6">six</option>
</select>
The final line $('#it option')[0].selected = 'selected';
is certainly executed in all browsers, at least if you put a console.log()
before and after it you will see them output to the console. So what is it about this structure that IE doesn't like?
Some answers suggested so far, that still do not work:
These solutions still have the exact same problem of not operating as expected in IE (v11).
change the line:
$('#it option')[0].selected = 'selected';
to:$('#it option')[0].prop('selected',true);
change the line:
}).appendTo( $('#it') );
to:}).detach().appendTo( $('#it') );