Reputation: 741
I have set up Algolia's autocomplete.js to search through multiple indices (‘resources’ and ‘users’). I want the link when a user clicks on a ‘resource’ to be different from when a user clicks on a 'user.'
Using Algolia's documentation for a jQuery implementation, 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 could I apply the .on('autocomplete.selected) function to each of the two sources separately?
Upvotes: 1
Views: 432
Reputation: 46
We've put an example for you that explains how to do so here.
on("autocomplete:selected", function(event, suggestion, dataset) {
// 1-indexed dataset
var url = datasets[dataset-1].url
// do something with:
console.log(url, suggestion);
// for example
// location.href = url + suggestion.objectID
});
If you have any other questions, you can also take a look at the Discourse forum.
Upvotes: 2