Skip to content
Home » Web » jQuery » jQuery Autocomplete Image

jQuery Autocomplete Image

Autocomplete Image

To show each image with each row in search results, jQuery Autocomplete needs to know more information about the images. For example, a returned JSON array of source, either local or remote, should contain not only value , but also image like this:

[{
  "value" : "Dove",
  "image" : "/images/dove.jpg"
}, {
  "value" : "Robin",
  "image" : "/images/robin.jpg"
}]

The value is for displaying names, and the image is for displaying images.

Let's see the jQuery code before modification.

  ...
  $("#bird").autocomplete({
    source : function(request, response) {
      $.getJSON("search.php", {
        query : request.term
      }, response);
    },
    minLength : 2,
    select : function(event, ui) {
      event.preventDefault();
      window.location.href = ui.item.url;
    }
  });
  ...

We append a piece of rendering code to $("#bird").autocomplete(...), which is highlighted below:

  ...
  $("#bird").autocomplete({
    source : function(request, response) {
      $.getJSON("search.php", {
        query : request.term
      }, response);
    },
    minLength : 2,
    select : function(event, ui) {
      event.preventDefault();
      window.location.href = ui.item.url;
    }
  }).data("ui-autocomplete")._renderItem = function(ul, item) {
    var rich_html = "<a><img src='" + item.image + "' />" + item.value + "</a>";
    return $("<li></li>").data("item.autocomplete", item).append(rich_html).appendTo(ul);
  };
  ...

This could be the simplest form to display images in the results. Of course, you can also add styles on search results as you like.

If you'd like to accept white or blank spaces in Autocomplete input box, you may refer to my post: How to Accept jQuery Autocomplete White Spaces in Search Box.

Leave a Reply

Your email address will not be published. Required fields are marked *