Pixabay autoComplete

Demos

Searching in local data

This plugin was designed mainly with AJAX requests in mind, but it may be used with local data, as well. Connecting the autocompletion suggester to an array of strings can be done in the source function like so:

new autoComplete({
    selector: 'input[name="q"]',
    minChars: 2,
    source: function(term, suggest){
        term = term.toLowerCase();
        var choices = ['ActionScript', 'AppleScript', 'Asp', ...];
        var matches = [];
        for (i=0; i<choices.length; i++)
            if (~choices[i].toLowerCase().indexOf(term)) matches.push(choices[i]);
        suggest(matches);
    }
});

The source function iterates through an array of (local) choices and we return a new array containing all (lowercased) matches. Simple as that.

AJAX requests

AJAX requests may come with very different requirements: JSON, JSONP, GET, POST, additionaly params, authentications, etc. In order to keep the source code small while retaining full flexibility, we decided to only use a simple callback function as the source for suggestions. Make your AJAX call inside this function and return matching suggestions with the response callback. For brevity, this example uses jQuery for AJAX:

new autoComplete({
    selector: 'input[name="q"]',
    source: function(term, response){
        $.getJSON('/some/ajax/url/', { q: term }, function(data){ response(data); });
    }
});

The AJAX call in this example needs to return an array of strings. The callback response must always be called, even if no suggestions are returned or if an error occured. This ensures the correct state of the autoComplete instance.

Optimizing AJAX requests

All search results are cached by default and unnecessary requests are prevented in order to keep server load as low as possible. To further reduce server impact, it's possible to abort unfinished AJAX requests before starting new ones. Again using jQuery's AJAX method for brevity:

var xhr;
new autoComplete({
    selector: 'input[name="q"]',
    source: function(term, response){
        try { xhr.abort(); } catch(e){}
        xhr = $.getJSON('/some/ajax/url/', { q: term }, function(data){ response(data); });
    }
});

By typing along, the user may trigger one AJAX request after the other. With this little trick, we make sure that only the most current one actually gets executed - if not done so already.

Advanced suggestions handling and custom layout

By making use of the renderItem() function, it's possible to turn the autocompleter into an item suggester:

new autoComplete({
    selector: 'input[name=&quot;q&quot;]',
    minChars: 1,
    source: function(term, suggest){
        term = term.toLowerCase();
        var choices = [['Australia', 'au'], ['Austria', 'at'], ['Brasil', 'br'], ...];
        var suggestions = [];
        for (i=0;i<choices.length;i++)
            if (~(choices[i][0]+' '+choices[i][1]).toLowerCase().indexOf(term)) suggestions.push(choices[i]);
        suggest(suggestions);
    },
    renderItem: function (item, search){
        var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
        return '<div class="autocomplete-suggestion" data-langname="'+item[0]+'" data-lang="'+item[1]+'" data-val="'+search+'"><img src="img/'+item[1]+'.png"> '+item[0].replace(re, "<b>$1</b>")+'</div>';
    },
    onSelect: function(e, term, item){
        alert('Item "'+item.getAttribute('data-langname')+' ('+item.getAttribute('data-lang')+')" selected by '+(e.type == 'keydown' ? 'pressing enter' : 'mouse click')+'.');
    }
});