0

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

1 Answer 1

1

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;
}

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your help :) but I'd like a select for each name. New York with option yes or not, Los Angeles with option yes or not
sorry - missed that - will amend my answer
No probs - happy to help - also just amended the answer to include values for the options as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.