Using Autocomplete with Multiple Indices and Different Links

I have set up autocomplete.js to search through multiple indices (‘resources’ and ‘users’, let’s say). I want the link when a user clicks on a ‘resource’ to go down one url path (http://www.example.com/resources/{id}, for example) and down a different url path (http://www.example.com/users/{id}, for example) if the user clicks on a result from the ‘users’ indice.

Using the documentation for jQuery, I have the following:

$('#aa-search-input').autocomplete(
  {
    hint: true,
    minLength: 2,
  }, [
    {
      source: $.fn.autocomplete.sources.hits(resources, { hitsPerPage: 3 }),
      displayKey: 'name',
      templates: {
        header: '<div class="aa-suggestions-category">Resources</div>',
        suggestion: function(suggestion) {
          return '<span>' +
          suggestion._highlightResult.name.value + '</span><span>'
          + suggestion._highlightResult.write_up.value + '</span>';
        },
      empty: '<div class="aa-empty">No matching resources <i class="frown icon"></i></div>',
    }
  },
  {
    source: $.fn.autocomplete.sources.hits(users, { hitsPerPage: 3 }),
      displayKey: 'name',
      templates: {
        header: '<div class="aa-suggestions-category">Users</div>',
        suggestion: function(suggestion) {
          return '<span>' +
            suggestion._highlightResult.username.value + '</span>';
          },
      empty: '<div class="aa-empty">No matching users <i class="frown icon"></i></div>',
      }
    }
  ]).on('autocomplete:selected', function(event, suggestion, dataset) {
    location.href = '/resources/view/show-' + suggestion.id;
});

How do I apply the .on('autocomplete.selected) function to the two sources separately?

Hello,

We’ve put together an example on Codepen that explains how to display an url based on the index the results are coming from.

Let us know if it helps!

With a little fandangling to match my specific use case, that worked beautifully. Thank you!

Similarly related, how could I truncate the output of the autocomplete to X characters? If I output my ‘write up’ data that is stored as text, it has the potential to be very long. I would like to show where the text matches but only show a small amount of the text to give the user context.

(Let me know if you would like me to post this as a new question.)

Awesome news!

Yes, for clarity’s sake, it would be better to open a new topic with a distinct title so that other users can find it more easily if they ask themselves the same question!

It’s not working on my localhost.