gafasmill gafasmill - 4 months ago 9
Javascript Question

Populating select shows 'undefined'

I am trying to populate a select from some data but it keep giving me undefined. The actual code works fine, I'm thinking its the format that's the problem?

Here's the code:

$.ajax({
url: 'myurlhere',
method: 'GET',
async: false,
success: function(result) {
$.each(result, function(result, value) {
$('#myselect').append($('<option>').text(value.id).attr('value', value.id));
});
}
});


Here is the Data:

{
"cars":[{
"id":"654",
"type": "ford"
},{
"id":"650",
"type": "fiat"
}]
}


How can I fix this?

Answer

You need to loop through result.cars, not result:

$.each(result.cars, function(i, value) {
    $('#myselect').append($('<option>', {
        text: value.id,
        value: value.id
    }));
});

Working example

Also note that it's incredibly bad practice to useasync: false - if you check the browser you'll see warnings about its use. You should remove it.