Search code examples
javascriptjqueryruby-on-railstypeahead.jsbootstrap-typeahead

How can I make typeahead fill in my searchbar with custom params?


I installed 'twitter-typeahead-rails' into my app and set it up so that when I begin to type into a search box, suggestions drop down. Then when I click on the suggestions, the search box is filled in. But right now, it gets filled in with the displayKey, as in the html that defines the suggestions:

<div class='typeahead-name' id='<user.name>'><user.name></div>

How can I get it to fill in the searchbar with only user.name?

Gemfile

gem 'twitter-typeahead-rails'

typeahead-ified searchbox

<%= form_tag users_path, :method => :get do %>
    <%= text_field_tag :search, params[:search], id:"typeahead" %>
    <%= submit_tag "Search" %>
<% end %>

<script type="text/javascript">
  // initialize bloodhound engine
  $(document).ready(function(){
    var bloodhound = new Bloodhound({
      datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.value);
      },
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      // sends ajax request to /typeahead/%QUERY
      // where %QUERY is user input
      remote: '/typeahead/%QUERY',
    });
    bloodhound.initialize();
    // initialize typeahead widget and hook it up to bloodhound engine
    // #typeahead is just a text input
    $('#typeahead').typeahead(null, {
      displayKey: function(user) {
        return "<div class='typeahead-name' id='" + user.name + "'>" + user.name + "</div>";
      },
      source: bloodhound.ttAdapter(),
    });
  });
</script>

routes

get 'typeahead/:query' => 'users#typeahead'

users__controller.rb

def typeahead
  q = params[:query]
  render json: User.where('name like ?, "%#{q}%")
end

Solution

  • Custom suggestions can be added like below as per the docs here

    templates: {
        suggestion: function (data) {
            return '<p><strong>' + data.value + '</strong> - ' + data.year + '</p>';
        }
    }
    

    These are the dropdown items that are rendered. displayKey is the one that is rendered in the textbox after something is selected from the dropdown.

    A displayKey can be rendered like this

    displayKey: function(state){
      return 'Selected is ' + state.val;
    }
    

    Here is a simple demo

    Hope this helps.