A great library for adding typeahead support to your site is Twitter’s Typeahead.js. Even better is the excellent Bloodhound suggestion engine which comes with it. Sometimes though if you’re dealing with a remote suggestion engine like Elasticsearch’s completion suggester you don’t need to run remote results once again through another suggestion engine. Bypassing Bloodhound is as simple as hooking your own source function into your Typeahead definition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$('input#keywords').typeahead({ highlight: true, }, { name: 'brands', display: 'value', source: function(query, syncResults, asyncResults) { $.get('/search?q=' + query, function(data) { asyncResults(data); }); } }) |
what a life saver! thx a mil for sharing!
btw – did you manage to circumvent the ‘fails to show results on 2 or more chars in querystring’ ?
eg:
data = { ‘m-1-1’, ‘m-2-1’, ‘m-2-2’ }
result.length on q= ‘m’ => 3
result.length on q= ‘m-2’ => 0
result.length is 2 from server (remote) but none are displayed :/
Sorry, I’m not entirely sure what you mean. So you’re returning 2 results from the server but none are being displayed? You need to make sure the JSON you return is formatted correctly for typeahead.js. I believe it wants the values like [{“value”: “m-1-1”},{“value”: “m-2-1”}] if that’s what you are returning.
oh – nice of you to get back to me on this one!
but I ‘meddled’ with the src – and made a PR on a small change to async (with limits set to 5 and having 5 answers back from the server, the current version of Typeahead.js does nothing good for shows :)
cheers
Beauty. Thanks ☺
So simple, but exactly the solution for my problem! I just started using Elasticsearch and I thought typeahead was just a little bit slower than what it should be!
Thank you so much for this post!
Good solution, if you want to send request after each character has been typed…
i get this error: suggestions.slice is not a function
Sadly I wouldn’t know what the fix for that would be.
I get the same one unfortunately :/
I’m guessing that the suggestions you’re returning might not be an array?
Hey! Very nice example. But.. did you notice that after 3 chars, for each char it fires a request? So… I made a hack for this situation:
https://uploads.disquscdn.com/images/ba27a2eabe43b93a13e880a97d7f40ca672d52298247cd6a892707d3a2b0fbbb.png
With this timeout you get time to finish what you want to search…
I ended up using underscore with its built-in debounce function to handle this. Just add
Example below.
very good! much more elegant :)