Created
July 22, 2024 17:52
-
-
Save lgrachov/90f2b063068cd044ff92bf6e45848747 to your computer and use it in GitHub Desktop.
Convert array to select
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
const selects = [ | |
{ | |
name: "Select 1", | |
options: ["Option 1", "Option 2"], | |
}, | |
{ | |
name: 'Select 2', | |
options: ['Option 1, 'Option 2'] | |
} | |
]; | |
function addSelect({ id, name, options }) { | |
const selectWrapper = document.createElement("div"); | |
const selectLabel = Object.assign(document.createElement("label"), { | |
innerHTML: name, | |
}); | |
const select = Object.assign(document.createElement("select"), { | |
id: id || name, | |
name, | |
}); | |
["", ...options].forEach((option) => | |
select.append( | |
Object.assign(document.createElement("option"), { | |
value: option, | |
innerHTML: option, | |
}), | |
), | |
); | |
selectWrapper.append(selectLabel); | |
selectWrapper.append(select); | |
document.body.appendChild(selectWrapper); | |
} | |
selects.forEach((select) => addSelect(select)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment