dublintech
dublintech

Reputation: 17785

How display error when there is no match using JQuery autocomplete?

JQuery has a cool autocomplete function. What I want is if there are no matching entries from the autocomplete (for example user types in zadasdasda) to flag this to the user because the user can only enter something in this particular field that matches a value from a set of values in database. Before someway says just use a picklist, there are too many possible entries (> 1,000). I just want to check there is nothing already out there to do this in JQuery before I write a callback to do it myself. I can't find anything just want to double check.

Thanks

Upvotes: 0

Views: 6860

Answers (2)

Samuel
Samuel

Reputation: 879

Perhaps this will help. Here is a way to do it if I understand your need.

In my case the autocomplete gets data from a server via Ajax.

$("#myselect").autocomplete({
  source: function(request, response) {
    $.ajax({
      url: searchUrl,
      dataType: "json",
      data: request,                    
      success: function (data) {
        // No matching result
        if (data.length == 0) {
          alert('No entries found!');
          $("#myselect").autocomplete("close");
        }
        else {
          response(data);
        }
      }});
    },
  dataType: "json",
  autoFill: false,      
  scroll: false,
  minLength: 2,
  cache: false,
  width: 100,
  delay: 500,           
  select: function(event, ui) { 
    //eventuallydosomething(ui.item.value);
    $("#myselect").autocomplete("close");
  } 
});

The part which interests you is when the data is returned from the server:

  success: function (data) {
      // If we get no matching result
      if (data.length == 0) {
        alert('No entries found!');
        $("#myselect").autocomplete("close");
      }

Upvotes: 3

Clyde Lobo
Clyde Lobo

Reputation: 9174

You can replace the autocomplete._response function with your own, and then call the default jQueryUI function

var __response = $.ui.autocomplete.prototype._response;
$.ui.autocomplete.prototype._response = function(content) {
    __response.apply(this, [content]);
    this.element.trigger("autocompletesearchcomplete", [content]);
};

And then bind an event handler to the autocompletesearchcomplete event (contents is the result of the search, an array):

$("input").bind("autocompletesearchcomplete", function(event, contents) {
    if(contents.length<1){
     $("#results").html("No Entries Found");
    }
   else{
      $("#results").html("");
   }
});

DEMO

Source of the example

Upvotes: 0

Related Questions