Steven
Steven

Reputation: 19425

How do I add "No results" item to my autocomplete?

If my jQuery autocomplete request returns empty, I want to add "No results" to the drop down list. But how exactly do I do this?

I have removed stuff to shorten / make the code simpler in this example:

$(element).autocomplete({
    source: function (request, response) {
        $.ajax({
            success: function (data) {
                response(data);
            }
        });
    },
    response: function(e, ui){
        if (ui.content.length === 0) {
         // Could I do something here?
        }
    },
    select: function(e, ui){
        // Do stuff here
        return false;
    }
// This is not triggered if DB returns empty
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
    return jQuery( "<li></li>" )
      .data( "ui-autocomplete-item", item )
      .append( "<a id='" + item.id + "'>"+ item.name + "</a>" )
      .appendTo( ul );
}

Upvotes: 1

Views: 1242

Answers (1)

chridam
chridam

Reputation: 103375

In your response object, add the following:

response: function(event, ui) {
    if (!ui.content.length) {
        var noResult = { 
             value: "", 
             label: "No results found" 
         };
         ui.content.push(noResult);                    
     } else {
        $("#message").empty();
     }
},

JSFiddle

Upvotes: 4

Related Questions