TheFrack
TheFrack

Reputation: 2873

jQuery-ui Autocomplete show all values if no matching value found

Is it possible with jQuery Auto-complete, to make it so that if there are 'source:' values available, but they don't match what you are typing, then just show all the sources at once?

IE, given the following code, if I type in "pineapple", how do you show all the programming languages instead of none of them?

<script>
$(function() {
    var availableTags = [
        "JavaScript",
        "Perl",
        "PHP",
        "Python",
        "Ruby"
    ];
    $( "#tags" ).autocomplete({
        source: availableTags
    });
});
</script>
<input type="text" id="tags" />

Upvotes: 2

Views: 2965

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272146

Use the source property with a custom function. The custom function shown below mimics autocomplete original behavior, searching for the typed text as substring inside available tags. If no match is found, all available tags are returned.

$(function() {
    var availableTags = [
        "JavaScript",
        "Perl",
        "PHP",
        "Python",
        "Ruby"
    ];
    $("#tags").autocomplete({
        source: function(request, response) {
            var term = request.term.toLowerCase();
            var matchingTags = $.grep(availableTags, function(tag) {
                return tag.toLowerCase().indexOf(term) >= 0;
            });
            response(matchingTags.length ? matchingTags : availableTags);
        }
    });
});​

demo here

Upvotes: 6

Naftali
Naftali

Reputation: 146310

Just write a custom source callback.

For example:

source: function(req, res){
    res(['w00t', 'yay']);
}

See DOCs

In your case (pseudocode):

source: function(req, res){
     //find `req` in array
     if not found:
     res(availableTags);
     else:
     res({subset of availableTags});
}

Upvotes: 3

Related Questions