0

I have a json object, and I want to get the specific value from each key like fetch_array in mysql. This is my json:

var jsonData = [{"Id":"1","Name":"Ariel"},
                {"Id":"2","Name":"Rick"}];

Then I want to loop them in a <select> tag with $.each function

<select>
<option value='//this should be Id key' >//this should be Name key </option>
</select>

How do I pass id into the value attribute and pass the name in the <option> tag?

2 Answers 2

2

It's not JSON, it's a javascript array containing objects, and you'd iterate as usual

var select = document.querySelector('select');

for (var i=0; i<jsonData.length; i++) {
    var option       = document.createElement('option');
    option.value     = jsonData[i].Id;
    option.innerHTML = jsonData[i].Name;

    select.appendChild(option)
}

FIDDLE

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

2 Comments

option.innerHTML == option.text ??
@Pilot - Both are supported in all major browsers, innerHTML is usually faster than the text methods, but it wouldn't really matter in this case, both would work just fine.
1

Simple, loop and create your options, then append:

var options = "";
for (var i = 0; i < jsonData.length; i++) {
    options += "<option value=" + jsonData[i].Id + ">" + jsonData[i].Name + "</option>";
}
$("#IDofSelect").append(options);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.