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

About budhramgurung

I am a self-motivated experienced Software Engineer with good communication and interpersonal skills and has the ability to work independently, can lead, motivate and influence others and can train and mentor others. Has hands-on experience in RoR since Jan, 2012. I am an open source contributor and holds a Master's Degree in Computer Science and experience working as a Software Engineer since August, 2011.

Posted on February 2, 2014, in javascript and tagged , , , , . Bookmark the permalink. 2 Comments.

  1. Re-initialization of datasets in typeahead.js fiddle does not work.
    Also, would like to know how you use prefetch with this.
    Regards.

  2. Updated the link Sachin.

    However, now I am not maintaining this wordpress blog.

    I have migrated to http://budhram.in/

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: