Created
December 2, 2020 22:21
-
-
Save buwilliams/8668598c29d7ba327a59328d8c956c8e to your computer and use it in GitHub Desktop.
Sorting select options
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
// Run this function after page load | |
// Example: sortOptions('select#wsl_categories option') | |
function sortOptions(selector) { | |
let $ = window.jQuery; | |
let options = jQuery(selector); | |
let arr = options | |
.map(function (_, option) { | |
return { | |
text: jQuery(option).text(), | |
value: option.value, | |
}; | |
}) | |
.get(); | |
arr.sort(function (option1, option2) { | |
return option1.text > option2.text | |
? 1 | |
: option1.text < option2.text | |
? -1 | |
: 0; | |
}); | |
options.each(function (i, o) { | |
o.value = arr[i].value; | |
jQuery(o).text(arr[i].text); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment