我有一个城市模型,该模型中有 81 个城市,只有 db 字段是名称。
我希望用户能够从导航栏中的下拉列表中选择一个城市,但用户也应该能够通过在开头输入几个字母来快速过滤这些城市。我想要做的确切示例在这个网站中:www.dabble.co
我不知道应该采取哪种方式来做到这一点。任何想法都欢迎。
最佳答案
如果您使用 JQuery,则有 http://selectize.github.io/selectize.js/ ,其中有一个国家/地区选择栏的示例。
您希望在 Controller 中访问您的城市集合,从而呈现您的表单。
例如
def new
@cities = City.all
end
您可以轻松添加对应的<select>
具有以下帮助器的表单标签:
<%= select_tag("cities",
options_from_collection_for_select(@cities, 'id', 'name'),
id: "selectize_cities" # sets the id of the select tag
)%>
根据您的 Javascript+Rails 设置,在需要 selectize.js 的所有组件后,您可以将其添加到您的 JavaScript 文件中
$("#selectize_cities").selectize();
如果您想手动实现此功能(无需 jQuery),一种方法是将数据传递到 html View 中的 div 标签并使用 Javascript 访问它
<%= div.tag(id: "selfmade", data_cities: @cities.to_json)%> #tag helper
const cities = JSON.parse(document.querySelector("#lol").getAttribute('data_cities')); //plain js
youtube 上还有一个 Railscasts“简单搜索表单”,它应该可以帮助您走得更远!
关于javascript - Rails 应用程序中搜索框的自动过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44221226/