Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing data source dynamically jQuery ui autocomplete on focus an entering characters

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!

like image 609
user3534513 Avatar asked Jan 31 '26 03:01

user3534513


1 Answers

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;
    }
});
like image 102
GregL Avatar answered Feb 01 '26 18:02

GregL