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 ); | |
} |
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
Didn't work for me, but this works - maybe the snippet is for older jquery