Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery autocomplete work with a dynamic array as source

I am currently trying to create an autocomplete with a source that is stored in a javascript variable but this variable can be updated by another function. So, what I would like is that at each time the user updates the autocomplete field, the source field of autocomplete is generated.

Here is the code I use:

<head>
    <script>
        var availableTags = ['java', 'javascript']
        // can be called anytime
        var addToTags = function(str){availableTags.push(str)}

        $(function() {
            $( "#tags" ).autocomplete({
                source: availableTags
            });
        });
    </script>
</head>
<body>
    <div class="ui-widget">
        <label for="tags">Tags: </label>
        <input id="tags" />
    </div>
</body>

Do I need to do a callback-like function?

like image 567
Christopher Chiche Avatar asked Dec 13 '12 09:12

Christopher Chiche


People also ask

How does autocomplete work in jQuery?

In the process of searching a specific value, the jQuery UI autocomplete selection feature provides the user with some string suggestions for the input area which effectively saves time. The autocomplete select action is triggered when the user selects one of the options from the pre-populated list.

How can create autocomplete search box in jQuery?

Syntax: $("TagId"). autocomplete({ source : itemList // List of Words. })


3 Answers

a source that is stored in a javascript variable but this variable can be updated by another function.

That should just work. If both the autocomplete and the updating function reference the same array, you can push new values at any time which will be used as soon as the array is evaluated next time (e.g. on keystroke).

I would like that at each time the user updates the autocomplete field, the source field of autocomplete is generated.

That's a different one. Yes, this needs a callback function to generate the source array dynamically, but that's simple. Have a look at the docs:

$( "#tags" ).autocomplete({
    source: function(request, resolve) {
        // fetch new values with request.term
        resolve(availableTags);
    }
});
like image 165
Bergi Avatar answered Oct 23 '22 19:10

Bergi


Just add a reset call to auto-complete in you addToTags function:

var addToTags = function(str){
   availableTags.push(str);
   $( "#tags" ).autocomplete({
       source: availableTags
   });
}
like image 44
Matanya Avatar answered Oct 23 '22 18:10

Matanya


this is very straight forward

$( "#tags" ).autocomplete('option', 'source', availableTags)

setting availableTags array wherever needed

like image 24
Azad Avatar answered Oct 23 '22 17:10

Azad