1

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>

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

This does the job, thanks.. but then what happens with the k on the function?
k will be the index of the current item, so on first iteration it will be 0, then second iteration it will be 1. For your particular requirement you don't need to use k for anything within your function, but it does need to be in the function declaration as a placeholder so that v is the second argument. Although now that I think about it you could leave out k and v and use this.code and this.name within the function...
0

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');
        });
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.