Reputation: 463
I don't know how to write this task. I'd like to creates dynamically different select inputs that have in common the option.
For example. My json file is that:
data.json
[{"name":"New York","value":"ny"},
{"name":"Los Angeles","value":"la"},
{"name":"Milan","value":"milan"},
{"name":"Rome","value":"rome"}]
The common option is:
<option value="yes"> yes </option>
<option value="no> no</option>
Through JS I'd like to create the select option for New York, the select option for Los Angeles etc... How can I do that? thank you in advance
Upvotes: 0
Views: 204
Reputation: 15509
Simply loop through the array and use the name and value properties of each array object to construct the options for the select list. Thne pass that to the select list.
EDIT - as indicated in the comments - the OP wants the various array items to be shown individually and have yes / no values. Answer amended to allow that.
var arr = [
{"name":"New York","value":"ny"},
{"name":"Los Angeles","value":"la"},
{"name":"Milan","value":"milan"},
{"name":"Rome","value":"rome"}
];
buildSelect();
function buildSelect() {
arr.forEach(function(item){
var label = document.createElement("label");
label.innerText = item.name;
var select = document.createElement("select");
var optYes = document.createElement("option");
optYes.textContent = 'Yes';
var optNo = document.createElement("option");
optNo.textContent = 'No';
select.appendChild(optYes);
select.appendChild(optNo)
document.querySelector('body')
.appendChild(label)
.appendChild(select);
})
}
label {
display: block
}
select {
display: block;
margin-bottom: 15px;
}
Upvotes: 1