Created
May 26, 2009 21:09
-
-
Save pnomolos/118302 to your computer and use it in GitHub Desktop.
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
/* | |
* | |
* Copyright (c) 2006-2009 Sam Collett (http://www.texotela.co.uk) | |
* Modified by Phil Schalm to allow custom sorting via a passed in function | |
* | |
*/ | |
$.fn.sortOptions = function(ascending) | |
{ | |
// get selected values first | |
var sel = $(this).selectedValues(); | |
var a = typeof(ascending) == "undefined" ? true : !!ascending; | |
this.each( | |
function() | |
{ | |
if(this.nodeName.toLowerCase() != "select") return; | |
// get options | |
var o = this.options; | |
// get number of options | |
var oL = o.length; | |
// create an array for sorting | |
var sA = []; | |
// loop through options, adding to sort array | |
for(var i = 0; i<oL; i++) | |
{ | |
sA[i] = { | |
v: o[i].value, | |
t: o[i].text | |
} | |
} | |
// sort items in array | |
if (typeof(ascending) == "function") { | |
sA.sort(ascending); | |
} else { | |
sA.sort( | |
function(o1, o2) | |
{ | |
// option text is made lowercase for case insensitive sorting | |
o1t = o1.t.toLowerCase(), o2t = o2.t.toLowerCase(); | |
// if options are the same, no sorting is needed | |
if(o1t == o2t) return 0; | |
if(a) | |
{ | |
return o1t < o2t ? -1 : 1; | |
} | |
else | |
{ | |
return o1t > o2t ? -1 : 1; | |
} | |
} | |
); | |
} | |
// change the options to match the sort array | |
for(var i = 0; i<oL; i++) | |
{ | |
o[i].text = sA[i].t; | |
o[i].value = sA[i].v; | |
} | |
} | |
).selectOptions(sel, true); // select values, clearing existing ones | |
return this; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment