Skip to content

Instantly share code, notes, and snippets.

@3emad
Created April 2, 2012 18:46
Show Gist options
  • Save 3emad/2286247 to your computer and use it in GitHub Desktop.
Save 3emad/2286247 to your computer and use it in GitHub Desktop.
Sort select:option list with a callback function
/**
credits to: http://stackoverflow.com/questions/1134976/how-may-i-sort-a-list-alphabetically-using-jquery
: http://stackoverflow.com/questions/278089/javascript-to-sort-contents-of-select-element
and a little hacks there by 3emad
**/
function sortUnorderedOption(select,callback_fun) {
selElem = document.getElementById(select);
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort(function(x,y){
var a = String(x).toUpperCase();
var b = String(y).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
});
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
if(typeof callback_fun != 'undefined'){
selElem = callback_fun(selElem);
}
return;
}
/** end function **/
/*
* EXAMPLE of a callback
* // the following example failed to keep the last index.
* i.e
* temp = selElem.options[0];
* selElem.options[0] = selElem.options[1];
* selElem.options[1] = temp
* return;
*/
var replace_index = function(selElem){ // callback used to change places of elements
var dash = selElem.options[0];
var all = selElem.options[1];
selElem.options[0] = new Option(all.innerHTML, all.value);
selElem.options[1] = new Option(dash.innerHTML, dash.value);
return selElem;
}
/** Usage **/
sortUnorderedOption('select_category',replace_index); // select_category is an ID of a select
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment