2

I have a JSON array grabbed using the code below:

$.getJSON("somelist.php", function( json ) {
  list = json;
});

somelist.php returns the following values:

[{"id":"1","name":"John Doe"},{"id":"2","name":"Jane Doe"}]

I also have a list box in the same page as shown:

  <div id="someid" class="someclass">
    <select id="someotherid" class="someotherclass">
    </select>
  </div>

How do I go about inserting the following options to someotherclass, between the select tags?

  <option value="1">John Doe</option>
  <option value="2">Jane Doe</option>

I have only done this using PHP before and it seems much more complicated to sort through using JS/jQuery.

1 Answer 1

2
var box = document.getElementById("someotherid");
list.forEach(function(item){
    var opt = document.createElement("option");
    opt.value = item.id;
    opt.innerHTML = item.name;
    box.appendChild(opt);
});

Something like this

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

1 Comment

This is also what I need, but I'd need to know what is the "item" here? Is it the objected from getJson? Thanks.

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.