Search code examples
javascriptjqueryjquery-uiautocompletejquery-ui-autocomplete

JQuery Autocomplete source not updating


I am using jquery-ui autocomplete plugin.

Here is how I've instantiated the autocomplete plugin.

//autofill
$( "#TextArea" ).autocomplete({
    source: "search.php?option="+ option.toLowerCase(),
    minLength: 3
});

On dropdown change, i am trying to change the option :

$('#Options').on('change',  function() {
        option = this.value.toLowerCase();
        var teaxtarea = $('#TextArea');
        //this is supposed to change the source string when the option value changes.
        teaxtarea.autocomplete( "option", "source", "search.php?option="+ option);
    }
});

I got the code to update the source string from the question below.

Jquery: Possible to dynamically change source of Autocomplete widget?

However, this solution doesn't seem to work for me.

I still get the first selected option even if I change the option in the dropdown.


Solution

  • Suggest the following:

    $("#TextArea").autocomplete({
        source: function(req, resp){
          var option = $('#Options option:selected').val().toLowerCase();
          $.ajax({
            cache: false,
            url: "search.php",
            data: {
              option: option,
              term: req.term
            },
            dataType: "json",
            success: function(data){
              resp(data);
            }
          });
        },
        minLength: 3
    });
    

    I think one issue is that if #Options is a <select> element, you need to find the selected child element:

    $("#Options option:selected")
    

    This ensures that you have the proper object and then you can call .val() upon it.

    That may resolve the issue for you. If not, continue on.

    Second, to ensure you are not caching, we can perform a more manual source capture.

    When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must support CORS). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results.

    So we replicate the same functionality with some added settings. So each time source is checked, the options will be checked and the term will be sent. We'll get the data back in JSON and send back to Autocomplete to be displayed.