-
-
Save pyjamasam/a298df8c8effaa53b2692610b90758f8 to your computer and use it in GitHub Desktop.
Sort a SELECT box's OPTIONs alphabetically
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
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