gafasmill gafasmill - 4 months ago 9
Ajax Question

Javascript/jQuery ajax Select not populating

I have the following jquery code, in which I'm trying to get some data using ajax and then populating a select which I placed in the body of my html document:

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


Result from the ajax call gets this data:

{
"651":{
"name":"somename",
"stts":{
"opt1":2,
"opt2":1,
"opt3":"0"
}
},
"659":{
"name":"someothername",
"stts":{
"opt1":2,
"opt2":1,
"opt3":"0"
}
}

}


And this is the html:

<select id="#myselect"></select>


I can see that the data is collected but it's not populating the SELECT.

What am I doing wrong?

Answer

You need to loop through the object and use properties to get the values to appear in the html. Ie: value.name:

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

Also as @Alex Kudryashev pointed out, your select element should be:

<select id="myselect"></select>
Comments