Twitter Bootstrap Typeahead gon gem and passing data from model into JS – in json format-Collection of common programming errors

I would like the names of my ‘firms’to be passed into an auto completing typeahead on a form.

I am using twitter bootstrap and the gon gem to pass the data into Json and make it available to the js.

However i cannot get the field to respond, i dont think that the data is available to the form and do not understand why.

my firms controller does the following assigning the names of the firms to a gon variable.

gon.firms = Firm.all.map &:name

My Application.html.erb has the following in its header to make the gon variable available to js.



    jQuery(document).ready(function() {
        $(.typeahead).typeahead({source:gon.firms});
    });
    

Then I have the form that I would like assign the typeahead to, I have assigned the class=”typeahead” to it.

 'get', :class => 'typeahead'  do %>
 'input-medium search-query', :placeholder => 'Firm name' %>
 nil ,:class => 'btn' %>

Finally the application.js file the relevant jquery as per the twitter bootstrap documentation.

$(function() {  
    $('.typeahead .input-medium search-query').typeahead({source:[gon.firms]});
}

My application .js also has the following libraries

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require twitter/bootstrap
//= require_tree .

I have checked that gon.firms is available as a variable, but the dev console has the following error

uncaught syntax error: Unexpected token

any ideas what may be causing this?

Is there anything obviously wrong?

  1. First make sure gon.firms is populated as you expect (check in your web dev tool console). Then while you’re there make sure there aren’t js errors as you type in the box. Finally, as per the docs, it looks like you want to attach the plugin to the text field, not the form:

    $('.typeahead .search-query').typeahead( { source: gon.firms } );
    
  2. This is because gon.firms is a ruby array not a js array.

    You can tranfer a string to js and then split it to a array like this:

    $(function() {
        var col = "".split(",");
        $(".search-query").typeahead({ source: col });
    });
    

Originally posted 2013-11-15 09:07:32.