Twitter's Typeahead And A Simple Autocomplete Solution
I recently had to implement an auto-complete feature on a website I was building. The website uses select2 for all selects/inputs and select2 does have any auto-complete feature that works well except it appears to be impossible to pre-load the input with a selected, saved value.
After wasting many hours trying to get initSelection
to fire, with not success, I moved on and decide to
use Twitter’s autocomplete solution known as Typeahead
I finally did get Typeahead to work properly to close the feature, but it certainly was not simple. In case any other people are trying to do the same thing, I have attempted to document the easiet way to integrate a auto-complete solution using this library.
The first step to setting up Typeahead is to download the single, minified js file and adding it your assets. After it has been added to your project, you need to setup an API call that will return the search results. I am currently using Django Tastypie for most of my APIs, create my search API endpoint there:
After the API endpoint has been defined and tested, it is pretty easy to setup Typeahead. Here is a snippet of code I used to point Typeahead at the new API endpoint:
I also setup a global dictionary to pass to the Typeahead constructor:
The one issue I ran into is Typeahead does not provide the ability out of the box to display the name of the venue but then store the id of the venue to send the server. The displayKey
attribute controls which dropdown is selected and shows up in the box, but this doesnt not work correctly. I am actually really surprised that this is the default setting because I would imagine almost everyone would want the selected item from the dropdown to display a name, but store an database id. Regardless, this snippet of code will fix the issue:
My solution to storing the id involves adding a hidden input <input name="venue_pk" type="hidden">
, and then adding a callback that listens to the selected event in the dropdown list. When an item is selected, I add the selected id to the hidden input and then an able to send it to the server in an HTTP POST call for saving in the database.
Anyways, this solution works for me, although it seems like a hack. If anyone else knows of a better way to do this, please let me know. There are multiple github issues I have found dealing with this issue, but this seemed like the simpliest solution to me.