How can a dropdown be stylized when using twitter bootstrap with simple_form in a Rails app?

China☆狼群 提交于 2019-12-08 10:00:32

One way to get stylized dropdowns with SimpleForm and Bootstrap is to use Bootstrap-Select. There is a Rails Gem for it; add to your Gemfile and do a bundle:

gem 'bootstrap-select-rails'

You need to add it to your stylesheet

@import "bootstrap-select";

and Javascript.

//= require bootstrap-select

Now, all you need to do is use input_html: {class: 'selectpicker'} in your existing f.input:

<%= f.input :category, :collection => ["one", "two", "three", "four"],
:input_html => {:class => 'selectpicker'}, :label => 'Send To', prompt: "Choose From List" %>

and then initialize the Javascript (which is a one-off regardless of how many selectpickers you have):

<%= javascript_tag "$('.selectpicker').selectpicker();" %>

Restart your app and your input dropdown should render with Bootstrap styling.

Some extra info that may be useful: you can disable the prompt item so that it cannot be selected from the dropdown by adding the disabled class to the item. I couldn't find any guidance on SimpleForm how to apply a style to one element of a collection but I came up with the below that does it to all such prompts:

<%= javascript_tag "$('li[data-original-index=0]').addClass('disabled');" %>

Replace

<%= f.input :category, :collection => ["one", "two", "three", "four"],:input_html => { :class => 'dropdown'}, :label => 'Send To', prompt: "Choose From List" %>

With

<%= f.input :category, :collection => ["one", "two", "three", "four"],:input_html => { :class => 'form-control'}, :label => 'Send To', prompt: "Choose From List" %>

.form-control is used to style select tags. All textual <input>, <textarea>, and <select> elements with .form-control are set to width: 100%; by default. Wrap labels and controls in .form-group for optimum spacing.

dropdown is not used for select tags. See details here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!