Sorting options elements alphabetically using jQuery
https://stackoverflow.com/q/12073270/1430996
by Jeromy French
HTML
<label for="groceries">Groceries (will sort)</label>
<select id="groceries" class='sort_me' size="4">
<option value='22'>Hamachi</option>
<option value='101'>Banana</option>
<option value='1'>Sugar Cane</option>
<option value='-2'>Palm Oil</option>
<option value='TP'>toilet paper</option>
<option value='tac'>Tacos</option>
<option value='4'>Seltzer Water</option>
<option value='L'>Lobster</option>
</select>
<label for="states">States (will sort)</label>
<select id="states" class='sort_me' size="4">
<option value='Va'>Virginia</option>
<option value='NC'>North Carolina</option>
<option value='AL'>Alabama</option>
<option value='SC'>South Carolina</option>
<option value='AK'>Alaska</option>
</select>
<label for="colors">Colors (will not sort)</label>
<select id="colors" size="4">
<option value='R'>Red</option>
<option value='O'>Orange</option>
<option value='Y'>Yellow</option>
<option value='G'>Green</option>
<option value='B'>Blue</option>
</select>
<br />
<button type="button" id="btnSortIt">Sort Options</button>
CSS
.all_done{
border: 4px solid #0c0;
}
label{
display: block;
}
select {
margin-bottom: 20px;
}
JavaScript
$.fn.extend({
sortSelect() {
return this.each(function(){
let $this = $(this),
original_selection = $this.val(),
$options = $this.find('option'),
arr = $options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort((o1, o2) => {
// sort select
let t1 = o1.t.toLowerCase(),
t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
$options.each((i, o) => {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
$this.val(original_selection);
})
}
});
$('#btnSortIt').on('click', function(){
//for things classed as ""...
$('.sort_me')
//sort the options alphabetically
.sortSelect()
//then change the border color of the original select items, to prove the custom function returns those items
.addClass('all_done');
});