Using Typeahead from Twitter Bootstrap in a form (formtastic)

后端 未结 2 1318
别那么骄傲
别那么骄傲 2021-01-31 23:58

How do I integrate a typeahead from bootstrap like this:



        
2条回答
  •  猫巷女王i
    2021-02-01 00:07

    In your controller

    def index
      @autocomplete_items = Model.all
    end
    

    In your view, just like you have with an additional ID for the selector...

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

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

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

    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.

提交回复
热议问题