Skip to content

Instantly share code, notes, and snippets.

@buwilliams
Created December 2, 2020 22:21
Show Gist options
  • Save buwilliams/8668598c29d7ba327a59328d8c956c8e to your computer and use it in GitHub Desktop.
Save buwilliams/8668598c29d7ba327a59328d8c956c8e to your computer and use it in GitHub Desktop.
Sorting select options
// 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