0

I'm passing list object from view to ajax autocomplete in template but unable to show the no Cars found in the drop down list

I'm passing a list object as 'No Cars Found' if no objects found in dB and if found the relevant objects are sent.But i Could see DB objects are shown in the dropdown but 'No Cars Found' is not shown in the Dropdown when no objects found.

    <
script type = "text/javascript" >

    jQuery(function complete() {
        $(".basicAutoComplete").on('keyup', function() {

            var value = $(this).val();
            $.ajax({
                url: "{% url 'ajax_autocomplete' %}",
                data: {
                    'search': value
                },
                dataType: 'json',

                success: function(data) {
                    var carslist = data.list;    

                    list = carslist;

                    $(".basicAutoComplete").autocomplete({
                        source: list,
                        minLength: 2,

                    });

                }
            });
        });
    });

<
/script>

View

def autocomplete(request):   
    if request.is_ajax():
        q=request.GET.get('search')
        queryset = Cars.objects.filter(car_model__istartswith=q).values('car_model')
        
        list = []        
        for i in queryset:
            list.append(i['car_model'])       


        if not list:
                list.append('No Cars Found')
  
        data = {
            'list': list,
        }
        return JsonResponse(data)
  

I need No Cars Found to be displayed in the dropdown when no matching cars found in DB.

Community
  • 1
  • 1
  • Instead of `if not list:` you'd need to check if the list is empty or not. `if len(list) == 0` or `if list == []` – art Jul 10 '19 at 13:32
  • @art05, thanks for your time .There is no problem with view, I'm able to retrieve the 'No Cars Found' list object back to the template when no matches found , but i'm unable to pass this to source(autocomplete) which would display in the search drop down. – Chaitanya Reddy Jul 10 '19 at 16:54

1 Answers1

0

Read the concept of autocomplete in query and thanks to Jquery Autocomplete - no result message Used a function for the source

  $(".basicAutoComplete").autocomplete({
        source: function(request, response) {
            var results = $.ui.autocomplete.filter(list, request.term);
        if (!results.length) {
            results = [NoResultsLabel];
        }

        response(results);
    },
    minLength: 2,

});