Skip to content

Instantly share code, notes, and snippets.

@cschlyter
Last active October 2, 2024 10:05
Show Gist options
  • Save cschlyter/5187131 to your computer and use it in GitHub Desktop.
Save cschlyter/5187131 to your computer and use it in GitHub Desktop.
[Javascript] Sort alphabetically the option elements of a select element by text.
function sortSelectOptions(selectElement) {
var options = $(selectElement + " option");
options.sort(function(a,b) {
if (a.text.toUpperCase() > b.text.toUpperCase()) return 1;
else if (a.text.toUpperCase() < b.text.toUpperCase()) return -1;
else return 0;
});
$(selectElement).empty().append( options );
}
@MightyPork
Copy link

MightyPork commented Sep 7, 2020

Didn't work for me, but this works - maybe the snippet is for older jquery

var options = $(selectElement + " option").toArray();
options.sort(function(a, b) {
  let aa = a.textContent;
  let bb = b.textContent;
  if (aa.toUpperCase() > bb.toUpperCase()) return 1;
  else if (aa.toUpperCase() < bb.toUpperCase()) return -1;
  else return 0;
});
$(selectElement).empty().append( options );

@hossein-babaei
Copy link

perfect

@Elcar86585
Copy link

Good

@stefanseeger
Copy link

stefanseeger commented Oct 2, 2024

In 2024 please simply use a.textContent.toLocaleUpperCase().localeCompare(b.textContent.toLocaleUpperCase()) instead of this if else stuff

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment