Last active
January 5, 2021 23:12
-
-
Save johndhancock/28978aa4549cfcd462a7a1fcbafee696 to your computer and use it in GitHub Desktop.
Populating an empty select element with values dynamically from data
This file contains hidden or 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
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