Karem
Karem

Reputation: 18123

Handle and turn the json data into options selector with jQuery

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

Answers (3)

VisioN
VisioN

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

zevero
zevero

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

The Alpha
The Alpha

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");
});​

DEMO.

Upvotes: 1

Related Questions