SaAn
SaAn

Reputation: 452

JQuery autocomplete - Unable to set the source dynamically

I am trying to do the following. I have a date picker. When I select a date (during data change event), I am doing a ajax call to get data that I need to populate in a autocomplete drop down. When the page loads for the first time, the autocomplete box will be empty. As and when the date is changed or selected, the autocomplete box should populate accordingly. Please check my code below.

When I initiate the dataSrc variable, the drop down loads for the first time without any issues. The issue that I am having is with the dynamic population, the data that I am fetching from the ajax call is not being set in the autocomplete source dynamically.

Please advice.

    var dataSrc = [];
    $(document).ready(function() {
        $("#dropdownselector").autocomplete({
            source : dataSrc,
            change : function(event, ui) {
                $("#selector").val(0);
                $("#selector").val(ui.item.id);
            }
        }).focus(function() {
            $(this).autocomplete("search", " ");
        });

    $('#dateselector').on("changeDate", function() {
        $.ajax({
            type : "GET",
            url : "../getDropDownData",
            data : {
                "dateSelected" : $('#dataSelected').val()
            },
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            dataType : "json",
            async : true,
            cache : false,
            success : function(data) {
                dataSrc = JSON.stringify(data);
            },
            error : function(data) {
                alert('There was an error while fetching data.')
            }
        })
    });
    });

Upvotes: 1

Views: 2141

Answers (2)

Taplar
Taplar

Reputation: 24965

dataSrc = JSON.stringify(data); replaces what dataSrc points to. It does not change the original array element that was given to the autocomplete.

You could try pushing all the elements from the data into the dataSrc, which would cause the array that dataSrc originally pointed to, to not change, but get new values.

Or if that does not work, you may have to use the https://api.jqueryui.com/autocomplete/#method-option method to change the source option for the autocomplete.

$("#dropdownselector").autocomplete( "option", "source", data);

Upvotes: 1

dev-cc
dev-cc

Reputation: 454

Inner your success function you need to destroy the old autocomplete and redraw it. Maybe, you need to create a function to create the autocomplete ('drawAutocomplete').

...
success : function(data) 
{
   dataSrc = JSON.stringify(data);

   $( "#dropdownselector" ).autocomplete( "destroy" );
   drawAutocomplete();
},
...

Upvotes: 0

Related Questions