Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyjamasam/a298df8c8effaa53b2692610b90758f8 to your computer and use it in GitHub Desktop.
Save pyjamasam/a298df8c8effaa53b2692610b90758f8 to your computer and use it in GitHub Desktop.
Sort a SELECT box's OPTIONs alphabetically
var SortSelect = function(select) {
var options = jQuery.makeArray(select.find('option'));
var sorted = options.sort(function($a, $b) {
jQuery(a).text() > jQuery(b).text()
var a = jQuery($a).text();
var b = jQuery($b).text();
var ax = [], bx = [];
a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });
while(ax.length && bx.length) {
var an = ax.shift();
var bn = bx.shift();
var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if(nn) return nn;
}
return ax.length - bx.length;
});
select.append(jQuery(sorted))
.prop('selectedIndex', 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment