I have a select box on a form, which carries an incremental rel attribute. I have a function that can sort the options by thier .text() value, into alphabetcal order.
<If you want to sort by rel you should change your function
$(this).html($("option", $(this)).sort(function(a, b) {
var arel = $(a).attr('rel');
var brel = $(b).attr('rel');
return arel == brel ? 0 : arel < brel ? -1 : 1
}));
edit with parseInt()
$(this).html($("option", $(this)).sort(function(a, b) {
var arel = parseInt($(a).attr('rel'), 10);
var brel = parseInt($(b).attr('rel'), 10);
return arel == brel ? 0 : arel < brel ? -1 : 1
}));
I needed a similar solution then made some changes to the original function and it worked fine.
function NASort(a, b) {
return (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) ? 1 : -1;
};
$('select option').sort(NASort).appendTo('select');
For future reference, the accepted answer is not complete if option
has data or props (e.g. .prop('selected', true)
). They will be removed after using .html()
.
The function below is probably not optimized but it's correctly working :
$.fn.sortChildren = function(selector, sortFunc) {
$(this)
.children(selector)
.detach()
.sort(sortFunc)
.appendTo($(this));
};
$('select').sortChildren('option', function(a, b) {
// sort impl
});
You can use the .attr() function to get the value of an attribute in jQuery. See http://api.jquery.com/attr/ for more info.
Try this:
$(object).each(function() {
// Keep track of the selected option.
var selectedValue = $(this).val();
// sort it out
$(this).html($("option", $(this)).sort(function(a, b) {
var aRel = $(a).attr("rel");
var bRel = $(b).attr("rel");
return aRel == bRel ? 0 : aRel < bRel ? -1 : 1
}));
// Select one option.
$(this).val(selectedValue);
});
Try this.
$(document).ready(function()
{
var myarray=new Array();
$("select option").each(function()
{
myarray.push({value:this.value, optiontext:$(this).text()});
});
myarray.sort(sortfun);
$newHmtl="";
for(var i=0;i<myarray.length;i++)
{
$newHmtl+="<option rel='1' value='"+myarray[i]['value']+"'>"+myarray[i]['optiontext']+"</option>";
}
$("select").html($newHmtl);
});
function sortfun(a,b)
{
a = a['value'];
b = b['value'];
return a == b ? 0 : (a < b ? -1 : 1)
}