How do I integrate a typeahead from bootstrap like this:
<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"]'>
into a standard form like this:
<%= 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 %>
In your controller
In your view, just like you have with an additional ID for the selector…
And most importantly, pass the
@autocomplete_itemsinstance variable defined in your controller into a Javascript variable in your view:This will serialize your data and make it usable JSON for the Typeahead function to use.
As for the Typeahead, simply pass that object (
@autocomplete_items) as JSON to the Javascript like so:Additionally there is an Autocomplete gem for Rails 3 which will work directly with your models rather than passing off the object to your Javascript. There is even a Formtastic example in the documentation.
Edit: It looks like I didn’t read your whole question! Unfortunately HTML5 Data Attributes are currently unsupported with Formtastic. There is however a separate branch that does include support for these attributes.
Other than that there’s always just sticking with Good ol’ HTML/ERB for dynamic features like this…
EDIT 2: I’ve just noticed two things. First being the way I was passing the JSON object to a Javascript variable (see the example). Secondly, the above example using HTML5 data attributes will not work with Twitter’s Typeahead plugin, but it will work with the jQuery UI Autocomplete plugin.