views:

250

answers:

1

I am using the jquery autocomplete plugin, but right now all it does is display a dropdown of rows that when clicked, injects the term into the input box.

What I want is for it to have a hyperlink, so when clicked, it redirects to the page.

Is it possible to return a more rich json request, that has other meta data like a url, image and would be displayed in the autocomplete box that displays?

I've seen this done on a site, but not sure if they had to modify the autocomplete plugin for it to work? i.e. returning a json response as oppose to just a list of text.

+1  A: 

If you're talking about this plugin, the following should work:

Assuming your json result looks something like this:

[
  {
    name: 'Google',
    image: 'http://google.com/logo.png',
    href: 'http://google.com'
  },
  {
    name: 'Bing',
    image: 'http://bing.com/logo.png',
    href: 'http://bing.com/'
  }
  ...
]

You will need to pass in your own custom parsing function inside your options. This function needs to return an array of objects of the format: { data: object, value: string, result: string }

$('#myfield').autocomplete('/search', {

  parse: function(data) {
    return $.map(data, function(item) {
      return { data: item, value: item.name, result: item.href };
    });
  },

  formatItem: function(item) {
    return '<img src="' + item.image + '"/> ' + item.name;
  }

})
.result(function(event, item) {
  location.href = item.href;
});

There might be a better way to do the link, and I know I've seen other autocomplete/suggest type plugins that allow you to do this easier but I don't remember which ones. Hope this helps.

scurker