Skip to content

Instantly share code, notes, and snippets.

@wehrhaus
Last active August 29, 2015 14:00
Show Gist options
  • Save wehrhaus/11008832 to your computer and use it in GitHub Desktop.
Save wehrhaus/11008832 to your computer and use it in GitHub Desktop.
Take a <select> object with a group of <options> that are sorted by a numeric value attribute and sort alphabetically by the text.
$(document).ready(function () {
var $selector = $('#selector'),
$options = $selector.find('option'),
sortedOptions = [], i;
for(i = 0; i < $options.length; i += 1) {
sortedOptions.push([$($options[i]).text(), i]);
}
sortedOptions.sort();
for(i = 0; i < sortedOptions.length; i += 1) {
var j = sortedOptions[i][1];
if (i === 0) {
$options[j].selected = true;
}
$selector.append($options[j]);
}
});
<!-- original -->
<select id="selector">
<option val="1">Beta</option>
<option val="2">Zed</option>
<option val="4">Alpha</option>
</select>
<!-- results -->
<select id="selector">
<option val="4">Alpha</option>
<option val="1">Beta</option>
<option val="2">Zed</option>
</select>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment