Skip to content

Instantly share code, notes, and snippets.

@cschlyter
Last active December 5, 2023 06:54
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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 );
}
@rlapenda
Copy link

good !

@Sago92
Copy link

Sago92 commented Oct 11, 2019

good and easy solution :) Thanks!

@boularbahsmail
Copy link

i can't understand , please i have a select of countries , any help ?

@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

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