JBK JBK - 4 months ago 9
JSON Question

How to create HTML select option from JSON

I have a JSON file

{
"1990": [ 1, 2, 3 ],
"1991": [ 4, 5, 6 ]
// and so on...
};


I have a HTML file I have loop through it because a have large amount of data.

<select name="year" id="year">
<option value="1990">1</option>
<option value="1990">2</option>
<option value="1990">3</option>
<option value="1991">4</option>
<option value="1991">5</option>
</select>


I have tried this way but it does not work for this does any suggest me how to solve it.

http://jsfiddle.net/MuGj7/

Thanks in advance and welcome suggestions.

Answer

Just iterate the object and append an option element for each iteration:

var obj = {
    "1990": [ 1, 2, 3 ],
    "1991": [ 4, 5, 6 ]  
};

for (var i in obj) {
  for (var y in obj[i]) {
    $('#year').append($('<option value="' + i + '">' + obj[i][y] + '</option>'));
  }  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="year" id="year"><select>