Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Autocomplete - no result message

I would like the autocomplete to display "no results" in it's drop down list if no result are found.

My situation is like the JQuery default example.

$(function() {
    var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
        ];
    $( "#tags" ).autocomplete({
        source: availableTags
    });
});

Thank you for your help.

like image 227
m14Grl Avatar asked Dec 29 '11 01:12

m14Grl


1 Answers

Here's one way you could accomplish this:

$(function() {
    var availableTags = [ /* snip */];  
    var NoResultsLabel = "No Results";

    $("#tags").autocomplete({
        source: function(request, response) {
            var results = $.ui.autocomplete.filter(availableTags, request.term);

            if (!results.length) {
                results = [NoResultsLabel];
            }

            response(results);
        },
        select: function (event, ui) {
            if (ui.item.label === NoResultsLabel) {
                event.preventDefault();
            }
        },
        focus: function (event, ui) {
            if (ui.item.label === NoResultsLabel) {
                event.preventDefault();
            }
        }
    });
});

Basically, you need to provide a function reference as the source to the autocomplete. Inside of that function, you can use the same utility function ($.ui.autocomplete.filter) to filter down the results. Then you can see if the results array is empty. If it is, you can add a default message to the results list.

The other two options I've specified prevent the No Results option from being selected or focused.

Example: http://jsfiddle.net/er6LF/

like image 136
Andrew Whitaker Avatar answered Sep 27 '22 00:09

Andrew Whitaker