Reputation: 592
I've implemented an application, in one the forms there are alot of data in its drop down field, it takes some time to load that page, so i want to load it in ajax call, but the calling back data not creating new option tag and append to select tag, here is what i tried
i tried all of these codes but non of them worked !
$(document).ready(function () {
$('#guestinfo').select2({
ajax: {
url: '{% url "booking:return_ajax_guests" %}',
dataType: 'json',
processResults: function (data) {
console.log(data.length)
if(data.length > 0){
for(i=0;i <= data.length;i++){
//var options = data[i].full_name
//console.log(options)
//$('#guestinfo').append("<option value='"+options+"'>"+options+"</option>")
//$('#guestinfo').trigger('change');
//var opts = new Option("option text", "value");
//$(o).html("option text");
//$("#guestinfo").append(o);
$('#guestinfo').append($('<option>', {
value: options,
text : options
}));
}
}
//return {
// results: $.map(data, function (item) {
// $('#guestinfo').append("<option value='"+item.full_name+"' selected>"+item.full_name+"</option>")
// $('#guestinfo').trigger('change');
// return {full_name: item.full_name, city: item.city__name};
// })
//console.log(results)
//};
}
},
minimumInputLength: 0
});
})
<div class="col-span-5 groupinput relative bglightpurple mt-2 rounded-xl">
<label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "full names" %}</label>
<select name="guestinfo" id="guestinfo" class="visitors w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white">
<option value="------">---------</option>
</select>
</div>
select2 version : 2.0.7 and here is my server side code (django)
@login_required
def return_ajax_guests(request):
if request.is_ajax():
term = request.GET.get('term')
all_guests = Vistor.objects.all().filter(full_name__icontains=term)
return JsonResponse(list(all_guests.values('full_name','city__name','dob')),safe=False)
the data shown in console very well! but i cant append it into select tag! is there something i've done wrong please ? thank you in advance .. updated data for the for loop in the console
console.log(options)
console.log(data)
Upvotes: 0
Views: 1866
Reputation: 6373
First, there is no need to manually create the options, select2 automatically creates them when supplied with the correct data.
With that been said, your data should be formatted in the form [{id: 'id', text: 'text'}, ...]
for it to work properly with select2.
Try this
$('#guestinfo').select2({
ajax: {
url: '{% url "booking:return_ajax_guests" %}',
dataType: 'json',
data: function(params){ // you can delete this part if you don't intend to filter the data on the server
return {
search: params.term, // search term
};
},
processResults: function (data, params) {
return {
results: data.map(({full_name}) => ({id: full_name, text: full_name}))
};
}
},
minimumInputLength: 0
});
Upvotes: 1