Home > Software engineering >  how to add new option for select tag in select2 - remote data
how to add new option for select tag in select2 - remote data

Time:02-19

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 >
    <label >{% trans "full names" %}</label>
    <select name="guestinfo" id="guestinfo" >
        <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) for loop names data console.log(data) console.log(data)

CodePudding user response:

Your idea of using Ajax is a good one. The problem, I think is right here

url: '{% url "booking:return_ajax_guests" %}',

The {% %} is used when you render a page in Django using the render function, which takes the url within the { % %} and replaces it with with variables in your view, your python django code.

The JavaScript loads AFTER Django renders the page, so this will actually generate the STRING '{% url "booking:return_ajax_guests" %}', which of course, is not what you want.

JQuery is not my strength, but you should be able to to pass the url in your Ajax call like this (I have use this using Vanilla JavaScript fetch, and it worked fine):

    url: 'booking:return_ajax_guests',

CodePudding user response:

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
});
  • Related