enriqg9
enriqg9

Reputation: 1507

Ajax add option to select for each json array

I need to populate a select item with the values that I get from an ajax call, I return such values as a json array. With the code below, the select is created without any options.

$.ajax({
  type: "GET",
  url: "/wp-content/gta/search_airport.php",
  data: {city: t_city}
}).done(function(resp){
  var sel = $('<select name="airport" id="slt">').appendTo('#pick_type');
  $.each(resp, function() {
$.each(this, function(k, v) {
$('<option>').val(k).text(v).appendTo('#slt');
   });
  });
});

Example json array

[{"name":"Los Angeles","code":"LAX"},{"name":"San Francisco","code":"SFO"}]

I would like the options to be something like <option value="LAX">Los Angeles</option>

Upvotes: 1

Views: 9001

Answers (2)

nnnnnn
nnnnnn

Reputation: 150030

You don't needed a nested $.each(). Just loop through the array and directly access the properties of the object at each index:

$.each(resp, function(k, v) {
    $('<option>').val(v.code).text(v.name).appendTo('#slt');
});

On the first iteration, v will be {"name":"Los Angeles","code":"LAX"}, so v.code will be "LAX". On the second iteration, v will be {"name":"San Francisco","code":"SFO"}, so v.code will be "SFO"...

(You may also need to add dataType:"json" to your $.ajax() options - if you don't specify jQuery tries to work it out from the response's MIME type.)

Upvotes: 3

Pranav C Balan
Pranav C Balan

Reputation: 115222

Try this,

$.ajax({
    type: "GET",
    url: "/wp-content/gta/search_airport.php",
    data: {city: t_city},
    dataType:"json"
}).done(function(resp) {
    var sel = $('<select name="airport" id="slt">').appendTo('#pick_type');
    $.each(resp, function(key,val) {
        $.each(val, function(k, v) {
            $('<option>').val(k).text(v).appendTo('#slt');
        });
    });
});

Upvotes: 0

Related Questions