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.
My question is, with jQuery, how do i sort in an ascending order using the rel attribute ?
<option rel="1" value="ASHCHRC">Ashchurch for Tewkesbury </option>
<option rel="2" value="EVESHAM">Evesham </option>
<option rel="3" value="CHLTNHM">Cheltenham Spa </option>
<option rel="4" value="PERSHOR">Pershore </option>
<option rel="5" value="HONYBRN">Honeybourne </option>
<option rel="6" value="MINMARS">Moreton-in-Marsh </option>
<option rel="7" value="GLOSTER">Gloucester </option>
<option rel="8" value="GTMLVRN">Great Malvern </option>
<option rel="9" value="MLVRNLK">Malvern Link </option>
my sort function: var object; can be one of many select boxes throughout the form.
$(object).each(function() {
// Keep track of the selected option.
var selectedValue = $(this).val();
// sort it out
$(this).html($("option", $(this)).sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}));
// Select one option.
$(this).val(selectedValue);
});
either pre-sort the results before you write the HTML (assuming it's dynamic and you are responsible for the output), or you write javascript. The Javascript Sort method will be your friend here. Simply pull the values out of the select list, then sort it, and put them back :-) Save this answer.
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
}));
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With