I have just finished testing a small plugin I created to sort <option> items in a <select> form field in-place. The assumption is that you do not have access to the source of the data - otherwise you would sort it before loading it.
I have used the plugin to sort a list with 288 items with no noticeable change in load time. I am, however, open to any suggestions to optimize this plugin.
(function($)
{
$.sortList = function(selector)
{
var __o = {s:[],o:{}};
var sel = (selector) ? selector : 'select';
$(sel + ' option').each(function(i,v)
{
__o.s.push($(v).attr('value'));
__o.o[$(v).attr('value')] = v; });
__o.s = __o.s.sort(function(a,b)
{
return b.toLowerCase() < a.toLowerCase();
});
$(sel).html('');
$.each(__o.s,function(l,w) { $(sel).append(__o.o[w]); }); }
}(jQuery);
Usage:
$.sortList('select[name=roles]');
EDITED
A better version:
- ( function( $ ) {
- $.fn.sortSelect = function( options ) {
- var def = $.extend({},{order:'asc'},options);
- var ret = { an: { 'asc': -1, 'desc': 1 }, bn: { 'asc': 1, 'desc': -1 } };
- return this.each( function() {
- var opt = $( this ).find( 'option' ).filter(function() { return this.value != ''; } ).sort( function( a, b ) {
- an = a.value.toLowerCase();
- bn = b.value.toLowerCase();
- if( an < bn ) {
- return ret.an[def.order];
- } else if( bn < an ) {
- return ret.bn[def.order];
- } else {
- return 0;
- }
- })
- .clone();
- $( this ).find( 'option' ).filter(function() { return this.value != ''; } ).remove();
- $( this ).append( opt );
- });
- };
- })( jQuery );
Usage:
- $( function() {
- $( 'select[name=country]' ).sortSelect( {order:'desc'} );
- });