Last active
August 29, 2015 14:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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]); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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