Show full list of suggestions on click with typeahead and bloodhound

2.8k views Asked by At

I am using Typeahead.js with the bloodhound suggestion engine and would like to make the list appear as soon as the user clicks in the search box.

I found this stackoverflow question (Twitter TypeAhead show all results programmatically) which is the same as me and the answer points to a jsfiddle solving the problem : http://jsfiddle.net/5xxYq/

Great.

However, it seems only to be working when not using bloodhound as the source for typeahead.

e.g. I forked their working example and switched the typeahead source to use bloodhound : http://jsfiddle.net/5xxYq/31/. The suggestion engine is working fine (when I type jo the list appears), but the little hack to make the suggestions appear on click does not seem to be working anymore.

Any idea on how to make the suggestions list appear on click with bloodhound?

Thanks!

2

There are 2 answers

4
Kuijkens On BEST ANSWER

If you are using this solution in combination with bloudhound you will need to alter bloodhound.js or the bundle.js as well.

In typeahead.bundle.js or bloodhound.js add find this code (line 450)

return matches ? _.map(unique(matches), function(id) {
                return that.datums[id];
            }) : [];

Add this check to return all suggestions if the token input is empty:

if (tokens == '') return that.datums;

It will now look like:

if (tokens == '') return that.datums;
return matches ? _.map(unique(matches), function(id) {
                    return that.datums[id];
                }) : [];

I have tested this in your fiddle and it works.

1
MJar On

I think there might be a better way of doing this. Without altering the bloodhound/boundle js, but it still depends on internal bloodhound implementation that may change.

var searchEngine = new Bloodhound({...});
function searchWithDefaults(q, sync) {
  if (q === '') {
    sync(searchEngine.index.all());
  } else {
    searchEngine.search(q, sync);
  }
}
$("#typeahead").typeahead({
  minLength : 0,
}, {
  name : 'typeahead',
  source : searchWithDefaults
});

This code takes advantage of implementation of Bloodbound internal search engine called SearchIndex and its function all() that returns full list of data stored by Bloodhound.

Answer inspired by: