Reputation: 29
var addColor = [
{
"option": "opt1",
"value": "empty",
"id": "white",
"name": "Color"
},
{
"option": "opt2",
"value": "#60afdc",
"id": "blue",
"name": "Blue #60afdc"
},
{
"option": "opt3",
"value": "#f4a700",
"id": "yellow",
"name": "Yellow #f4a700"
},
{
"option": "opt4",
"value": "#c70049",
"id": "ruby",
"name": "Ruby-red #c70049"
},
{
"option": "opt5",
"value": "#000",
"id": "black",
"name": "Black #000"
},
]
function addCol() {
console.log(addColor);
addColor.forEach((opt, i) => {
**opt1**.setAttribute('value', `${opt.value}`);
**opt1**.setAttribute('id', `${opt.id}`);
**opt1**.innerHTML = `${opt.name}`;
select.appendChild(**opt1**);
});
}
addCol();
How do I get the opt1 to add up? I have tried to add, ${opt.option}
there but that dosent work.
Is there any nicer way to do this? I want to be able to add value, id and name, easily if I came up with a new color in my dropdown.
Upvotes: 0
Views: 110
Reputation: 482
const select = document.getElementById('select');
function addCol() {
addColor.forEach((opt, i) => {
let op = document.createElement('option');
op.value = opt.value;
op.innerHTML = opt.name;
op.id=opt.id;
select.appendChild(op);
});
}
addCol();
Upvotes: 2
Reputation: 1237
I am guessing your requirement is to create some option tags and append to select -
Do this in your foreach loop-
addColor.forEach((opt) => {
var option = document.createElement('option')
option.setAttribute('value', opt.value);
option.setAttribute('id', opt.id);
option.innerHTML = opt.name;
select.appendChild(option);
});
Upvotes: 2
Reputation: 50291
You can create option
using document.createElement
and add necessary attributes
var addColor = [{
"option": "opt1",
"value": "empty",
"id": "white",
"name": "Color"
},
{
"option": "opt2",
"value": "#60afdc",
"id": "blue",
"name": "Blue #60afdc"
},
{
"option": "opt3",
"value": "#f4a700",
"id": "yellow",
"name": "Yellow #f4a700"
},
{
"option": "opt4",
"value": "#c70049",
"id": "ruby",
"name": "Ruby-red #c70049"
},
{
"option": "opt5",
"value": "#000",
"id": "black",
"name": "Black #000"
},
]
const select = document.getElementById('select');
function addCol() {
addColor.forEach((opt, i) => {
const currElem = document.createElement('option');
currElem.setAttribute('value', `${opt.value}`);
currElem.setAttribute('id', `${opt.id}`);
currElem.innerHTML = `${opt.name}`;
select.appendChild(currElem);
});
}
addCol();
<select id='select'></select>
Upvotes: 0