I'm looking for clarification on why this issue is happening, and what should be done to avoid this behaviour.
I have a select
that will add new options on an event trigger. When this trigger fires I want to create a new option
append to the select
and then sort all the options in to an order (alphabetical or otherwise, does not matter for this issue). When I do this using the code below, the option
is added to the select
however the new option becomes selected even though a different option
is the "selected" option
.
$(function() {
var select = $('select');
select.append("<option value='9'>Nine</option>"); // This will become selected
select.html(select.find('option').sort(function(x, y) {
return $(x).text() > $(y).text() ? 1 : -1;
}));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper">
<select>
<option>Choose a number</option>
<option value="3">Three</option>
<option value="1">One</option>
<option value="0">Zero</option>
<option value="2" >Two</option>
<option value="8" selected="true">Eight</option>
</select>
</div>
Edit: The issue here is not that the options will be organized in one manner or another. The issue is that after the options are sorted the select displays the wrong option as the selected option. After the JS runs I would expect that Eight is still the selected option.