Skip to content

Instantly share code, notes, and snippets.

@johndhancock
Last active January 5, 2021 23:12
Show Gist options
  • Save johndhancock/28978aa4549cfcd462a7a1fcbafee696 to your computer and use it in GitHub Desktop.
Save johndhancock/28978aa4549cfcd462a7a1fcbafee696 to your computer and use it in GitHub Desktop.
Populating an empty select element with values dynamically from data
export default function (values) {
// sort value strings alphabetically
values.sort((a, b) => {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
});
// find select element/elements
const selects = document.querySelectorAll('<<selector name>>');
// add options for each value to selects
selects.forEach((s) => {
values.forEach((v) => {
const thisSelect = s;
thisSelect.innerHTML += `<option value='${v.toLowerCase()}'>${v}</option>`;
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment