Sorting Options Elements Alphabetically Using Jquery

Sorting options elements alphabetically using jQuery

What I'd do is:

  1. Extract the text and value of each <option> into an array of objects;
  2. Sort the array;
  3. Update the <option> elements with the array contents in order.

To do that with jQuery, you could do this:

var options = $('select.whatever option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});

Here is a working jsfiddle.

edit — If you want to sort such that you ignore alphabetic case, you can use the JavaScript .toUpperCase() or .toLowerCase() functions before comparing:

arr.sort(function(o1, o2) {
var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();

return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});

How may I sort a list alphabetically using jQuery?

You do not need jQuery to do this...

function sortUnorderedList(ul, sortDescending) {
if(typeof ul == "string")
ul = document.getElementById(ul);

// Idiot-proof, remove if you want
if(!ul) {
alert("The UL object is null!");
return;
}

// Get the list items and setup an array for sorting
var lis = ul.getElementsByTagName("LI");
var vals = [];

// Populate the array
for(var i = 0, l = lis.length; i < l; i++)
vals.push(lis[i].innerHTML);

// Sort it
vals.sort();

// Sometimes you gotta DESC
if(sortDescending)
vals.reverse();

// Change the list on the page
for(var i = 0, l = lis.length; i < l; i++)
lis[i].innerHTML = vals[i];
}

Easy to use...

sortUnorderedList("ID_OF_LIST");

Live Demo →

Sorting select list of options alphabetically in Javascript

$.getJSON("php/countryBorders.geo.json", (data) => {
$select.html("");

const features = data["features"].sort((a,b) => {
return (
(a.properties.name < b.properties.name && -1) ||
(a.properties.name > b.properties.name && 1) ||
0
);
});

features.forEach(feature => {
$select.append(`<option value="${feature.properties.iso_a2}">${feature.properties.name}</option>`);
});
});

How do I re-order the <options> alphabetically in a jquery-chosen dropdown

You should sort the list first... Then run the chosen plugin.

// sort list
var my_options = $("#my-dropdown option");
my_options.sort(function(a,b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
else return 0
})
$("#my-dropdown").empty().append(my_options);

// run chosen plugin
$("#my-dropdown").chosen({no_results_text: "No results matched"});

List sorting code pilfered from the highly rated answer here:

What is the most efficient way to sort an Html Select's Options by value, while preserving the currently selected item?

Sort Select Options by Value Attribute Using jQuery

var selectList = $('#featuredSelectField option');

selectList.sort(function(a,b){
a = a.value;
b = b.value;

return a-b;
});

$('#featuredSelectField').html(selectList);

Here you cand find a demo and compare the results with the original:
http://jsfiddle.net/74c2M/3/

Here you can find the proper code:
http://jsfiddle.net/74c2M/4/

Good luck !

Sort Options in a Select List with javascript/jQuery.. but not alphabetically

demo: http://jsfiddle.net/4bvVz/

function NASort(a, b) {    
if (a.innerHTML == 'NA') {
return 1;
}
else if (b.innerHTML == 'NA') {
return -1;
}
return (a.innerHTML > b.innerHTML) ? 1 : -1;
};

$('select option').sort(NASort).appendTo('select');

How to sort select alphabetically which contains optgroup?

You could do it with vanilla JS like this. I placed some of the last items in the dropdown as the first items, just to demonstrate.

If you give all of them labels then you can do it like this:

function sortStuff(arr) {  arr.sort((a, b) => {    if (a.label < b.label) {      return -1;    } else if (a.label > b.label) {      return 1    }    return 0;  })  return arr}
var select = document.querySelector('select')var options = [...select.children]var sortedOptions = sortStuff(options)
select.innerHTML = ''sortedOptions.forEach(i => select.append(i))sortedOptions[0].setAttribute('selected', 'true')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><select id="property-area" name="property_area" class="selectpicker" data-style="btn btn-primary btn-round" data-live-search="true" tabindex="-98">  <option value="1218" label="Umbria">Umbria</option>  <option value="1205" label="Sorrento Coast">Sorrento Coast</option>  <option value="1208" label="Amalfi Coast">Amalfi Coast</option>  <option value="1224" label="Apulia">Apulia</option>  <optgroup data-id="1221" label="Tuscany">    <option value="1302" data-parent-id="1221">Arezzo</option>    <option value="1299" data-parent-id="1221">Argentario</option>    <option value="1270" data-parent-id="1221">Chianti</option>    <option value="1261" data-parent-id="1221">Florence</option>    <option value="1297" data-parent-id="1221">Lucca & Pisa</option>    <option value="1290" data-parent-id="1221">Maremma</option>    <option value="1283" data-parent-id="1221">Siena</option>    <option value="1330" data-parent-id="1221">Val D'Orcia</option>  </optgroup>  <option value="1213" label="Capri Island">Capri Island</option>  <option value="1249" label="Cilento Coast">Cilento Coast</option>  <option value="1215" label="Como Lake">Como Lake</option>  <option value="1253" label="Garda Lake">Garda Lake</option>  <option value="1334" label="Ischia Island">Ischia Island</option>  <option value="1257" label="Maggiore Lake">Maggiore Lake</option>  <option value="1234" label="Rome City">Rome City</option>  <option value="1308" label="Sicily">Sicily</option></select>


Related Topics



Leave a reply



Submit