Reputation: 18123
So I have a $.post
, that returns some json_encode($array);
$array
is one dimensional, and it contains numbers: 2, 4, 6.
So now data
is holding the json data, how can I loop through and make options to my #time
selector? The value=""
and display text should be the number from the array.
Upvotes: 1
Views: 159
Reputation: 145478
Something like that should work:
$.each(data, function(i, val) {
$("<option />").text(val).val(val).appendTo("#time");
});
DEMO: http://jsfiddle.net/tmSqR/
UPDATE. Your data is not decoded from string format to JSON. Either add dataType
property to $.post
, or use data = JSON.parse(data)
before making iteration.
DEMO: http://jsfiddle.net/tmSqR/1/
Upvotes: 1
Reputation: 2412
Maybe you want to do this:
var s = $('select#time');
s.empty();
$.each(data, function(key, value){
s.append($("<option />").text(value).val(key);
//or
s.append($("<option value="key">value</option>");
});
Upvotes: 1
Reputation: 146269
Actually Data returned by json_encode($array)
from PHP
is a string in javascript and needs to be converted to an object first to loop through it so use $.parseJSON
before the loop begins
var obj=$.parseJSON(data);
$.each(obj, function(k, v) {
$("<option />").text(v).val(v).appendTo("#time");
});
Upvotes: 1