Monthly Archives: February 2014

Re-initialization of datasets in typeahead.js

typeahead.js is one of autocomplete search plugin inspired by twitter.com.

I have been using it quite from a while in my projects and had wonderful experience so far until I encountered with one requirement.

Requirement: Remove the selected data from dataset and don’t show it in next autosearch suggestions.

I used $(‘.typeahead’).typeahead(‘destroy’); as suggested but it didn’t work as expected.

It reverts the input element back to its original state but again adding typeahead feature to this same input with new dataSets doesn’t remove the autocomplete suggestions with new dataSets.

While googling for few hours for the ideal solution I found one good solution out of the discussion made in this github issue thread.

So following is solution I used and it works like charm!!! 🙂

Steps I followed for the solution:

  • Define a function to enable typeahead functionality as:
      function enable_auto_complete(name, dataSets){
        $('#typeahead_input_element').typeahead({
          name: name,
          local: dataSets
        });
      }  
    
  • Initialize the input with typeahead for first time with some name.
  • Remove the selected name from global ‘dataSets’.
  • Destroy typeahead feature as :
      $('#typeahead_input_element').typeahead('destroy')
    
  • Initialize the input again with typeahead but with different name and updated dataSets.

Working JSFiddle Link.

Advertisements