Marcos Belunti Marcos Belunti - 2 months ago 21
jQuery Question

Javascript populating list into html select repeating list twice

I am using jquery ajax to populate a html select.
The populating actually works but the problem is that for some reason the whole list is being added twice instead of just once.

Here is the code:

myfunction: function() {
$.ajax({
url: 'the-url-here',
method: 'GET',
success: function(result) {
$.each(result.cars, function(result, value) {
if (value.active === '1'){
$('#myselect').append($('<option>').text(value.name).attr('value', value.id));
}
});
}
});
}


How can I fix this so it's only populated once and not twice?

Answer

myfunction is being called twice somewhere, and since an append does what it is supposed to do (appends to your list), it's working as intended :)

Check if the value is already added before trying to add it:

$.each(result.cars, function(result, value) {
                if (value.active === '1' && $('#myselect option[value='+ value.id +']').length == 0) {
                    $('#myselect').append($('<option>').text(value.name).attr('value', value.id));
                }
            });