Grzegorz Węgorzewski Grzegorz Węgorzewski - 15 days ago 5
jQuery Question

How to bind json data

I've json response from server looks like that

{
"117":{
"09:00":5,
"10:00":5,
"11:00":5,
"12:00":5,
"13:00":5,
"14:00":5,
"15:00":5,
"16:00":5,
"17:00":5,
"18:00":5,
"19:00":5
}
}


How I can bind this to normal select to looks like that

<select name="time" id="time">
<option value="5">09:00</option>
<option value="5">10:00</option>
<option value="5">11:00</option>
</select>


Hours are not always the same, could be from 11:00 to 21:00.
Any idea how to display this in php or bind by jquery.
Thank you for response

Answer

Use a loop:

var objString = '{"117": {"09:00": 5,"10:00": 5,"11:00": 5,"12:00": 5,"13:00": 5,"14:00": 5,"15:00": 5,"16:00": 5,"17:00": 5,"18:00": 5,"19:00": 5}}';
var obj = JSON.parse(objString);
$.each(obj["117"], function(i, v) {
  $('#time').append('<option value="' + v + '">' + i + '</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="time"></select>

Comments