[Answered ]-Populating select box with Ajax and Jquery from queryset in Django

2👍

If your JSON is valid, you should use data (not data[0]) and your problem is most likely here:

$('select[name=category]').append('<option value="' + this.key + '">' + this.value +'</option>');

The this keyword in $.each returns the value, but as an object. See:
http://api.jquery.com/jquery.each/

The value can also be accessed through the this keyword, but
Javascript will always wrap the this value as an Object even if it is
a simple string or number value.

So this.key and this.value will give you undefined.

This should work (again, assuming your JSON is valid):

success: function(data){
    $.each(data, function(key, value){
        $('select[name=category]').append('<option value="' + key + '">' + value +'</option>');
    });
}

Leave a comment