Using Typeahead from Twitter Bootstrap on a form (formtastic)

How to integrate typeahead from bootstrap as follows:

<input type="text" class="span3" style="margin: 0 auto;" data-provide="typeahead" data-items="8" data-source='["University of Pennsylvania","Harvard","Yale","Princeton","Cornell","Brown","Columbia","Dartmouth"]'> 

in standard form:

 <%= semantic_form_for(@education) do |f| %> <%= render 'shared/error_messages', object: f.object %> <div class="field"> <%= f.input :college, placeholder: "Update Education" %> </div> <%= f.submit "Submit", class: "btn btn-large btn-primary" %> <% end %> 
+6
source share
2 answers

In your controller

 def index @autocomplete_items = Model.all end 

In your view, as with you with an extra identifier for the selector ...

 <% semantic_form_for(@education) do |f| %> <%= render 'shared/error_messages', object: f.object %> <div class="field"> <%= f.input :college, placeholder: "Update Education", id: "auto_complete" %> </div> <%= f.submit "Submit", class: "btn btn-large btn-primary" %> <% end %> 

And most importantly, pass the @autocomplete_items instance variable defined in your controller to the Javascript variable in your view:

 <%= javascript_tag "var autocomplete_items = #{ @autocomplete_items.to_json };" %> 

This will serialize your data and make it suitable for using JSON for the Typeahead function.

As for Typeahead, just pass this object ( @autocomplete_items ) as JSON for Javascript like this:

 <script type="text/javascript"> jQuery(document).ready(function() { $('#auto_complete').typeahead({source: autocomplete_items}); }); </script> 

In addition, there is an autocomplete stone for Rails 3 that will work directly with your models, rather than transferring the object to your Javascript. There is even a Formtastic example in the documentation.

Edit: Looks like I haven't read your whole question! Unfortunately, HTML5 data attributes are not currently supported by Formtastic. However, there is a separate branch that includes support for these attributes.

Also, they always just stick with Good ol 'HTML / ERB for dynamic functions like this ...

 <input type="text" class="span3" style="margin: 0 auto;" data-provide="typeahead" data-items="8" data-source='<%= @autocomplete_items.to_json %>'> 

EDIT 2: I just noticed two things. First of all, I passed the JSON object to a Javascript variable (see Example). Secondly, the above example using HTML5 data attributes will not work with the Twitter Typeahead plugin, but it will work with the jQuery UI Autocomplete plugin .

+6
source

I worked like:

controller

  @categories = Category.find(:all,:select=>'name').map(&:name) 

and views

 <input type="text" class="span3" style="margin: 0 auto;" data-provide="typeahead" data-items="8" data-source='<%= @categories.to_json %>'> 
+2
source

Source: https://habr.com/ru/post/911237/


All Articles