Last active
October 2, 2024 10:05
-
-
Save cschlyter/5187131 to your computer and use it in GitHub Desktop.
[Javascript] Sort alphabetically the option elements of a select element by text.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
} |
i can't understand , please i have a select of countries , any help ?
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 );
perfect
Good
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
good and easy solution :) Thanks!