我如何像这样从 Bootstrap 中集成 typeahead:
<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"]'>
变成这样的标准形式:
<%= 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 %>
最佳答案
在你的 Controller 中
def index
@autocomplete_items = Model.all
end
在您看来,就像您为选择器添加了一个额外的 ID...
<% 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 %>
最重要的是,将 Controller 中定义的 @autocomplete_items
实例变量传递给 View 中的 Javascript 变量:
<%= javascript_tag "var autocomplete_items = #{ @autocomplete_items.to_json };" %>
这将序列化您的数据并使其成为可用于 Typeahead 函数的 JSON。
至于 Typeahead,只需将该对象 (@autocomplete_items
) 作为 JSON 传递给 Javascript,如下所示:
<script type="text/javascript">
jQuery(document).ready(function() {
$('#auto_complete').typeahead({source: autocomplete_items});
});
</script>
另外还有一个 Autocomplete gem for Rails 3这将直接与您的模型一起使用,而不是将对象传递给您的 Javascript。文档中甚至还有一个 Formtastic 示例。
编辑:看来我没有读完您的整个问题!不幸的是,Formtastic 目前不支持 HTML5 数据属性。但是有一个 separate branch这确实包括对这些属性的支持。
除此之外,对于像这样的动态特性,总是坚持使用 Good ol' HTML/ERB...
<input type="text" class="span3" style="margin: 0 auto;" data-provide="typeahead" data-items="8" data-source='<%= @autocomplete_items.to_json %>'>
编辑 2: 我刚刚注意到两件事。首先是我将 JSON 对象传递给 Javascript 变量的方式(参见示例)。其次,上述使用 HTML5 数据属性的示例不能与 Twitter 的 Typeahead 插件一起使用,但它可以与 jQuery UI Autocomplete 一起使用。插入。
关于ruby-on-rails - 在表单中使用来自 Twitter Bootstrap 的 Typeahead (formtastic),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9794306/