0

In this basic example using jQuery autocomplete:

$("#textboxid").autocomplete(
    {
        source: testdata,
        delay: 100,
        minLength: 1
    });

where testdata is a local array of data, what is the recommended way to have any changes to the underlying source array, reflect in the autocomplete options?

Currently, if I subsequently add a new item to the testdata array (i.e. after the autocomplete has already been setup on the textbox element), I don't see that new option in the autocomplete list. If I dynamically add a new textbox to the page and set up for autocomplete, it does see the new option. But existing elements do not.

2 Answers 2

1

The most flexible way is to use a callback as the source, which polls your array/object/server for the data and returns the appropriate response.

Here is an example of how you could test this:

var testdata = ["foo","bar","baz","quux"];
$("#textboxid").autocomplete({
    source: function(request, callback) {
        var possiblematches = testdata.filter(function(v) {
            return v.match($.ui.autocomplete.escapeRegex(request.term));
        });
        callback(possiblematches);
    },
    delay: 100
});

A demonstration: http://jsfiddle.net/Eeg5L/. Documentation and further information for the source option can be found here.

Alternatively, you could reset the source after modifying the array using:

$("#textboxid").autocomplete("option","source", testdata);

I'd recommend using a setter for your array that does this automatically whenever you modify the array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - works nicely. Decided this route was the best all round, instead of "reapplying" the autocomplete each time.
0

When you update testdata run this :

$('#textboxid').autocomplete('option', 'source', testdata);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.