3

I am trying to get try to use different data source option for the input box using jQuery Autocomplete.

I have input box with id #polysearch. I would like to autocomplete the intput box on focus (just putting the cursor) with source option 'data1' and I would like to autocomplete the input box with source option 'data2' when typing 2 characters. Please help!

Thank you!

1 Answer 1

5

By utilising the source option for autocomplete, you can customise what array you want to use based on the length of the request.term (what the user typed into the box).

You also need to manually invoke the autocomplete's search method when the input is focused, to have it open on focus.

Here is the code I had to make this work. See it in action.

$(function() {
    var data1 = 'abcdefghijklmnopqrstuvwxyz'.split('');
    var data2 = 'cat dog fish shark unicorn sasquatch flamingo dingo snake mouse rat'.split(/\s+/g);

    $('#in').autocomplete({
        minLength: 0, // so it shows straight away without typing anything
        source: function (request, response) {
            if ((request.term || '').length <= 1)
               response(filter(data1, request.term));
            else
               response(filter(data2, request.term));
        }
    }).on('focus', function () {
        $(this).autocomplete('search', '');
    });

    function filter(array, searchTerm) {
        var matchingItems = [];
        for (var i = 0; i < array.length; i++) {
            if (array[i].indexOf(searchTerm.toLocaleLowerCase()) >= 0)
                matchingItems.push(array[i]);
        }
        if (matchingItems.length === 0)
            return ['No Matches'];
        return matchingItems;
    }
});
Sign up to request clarification or add additional context in comments.

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.