How to control the size of the select box in Ruby on Rails 3?
Solution 1
The basic synatx for select is
select(object, method, choices, options = {}, html_options = {})
Options are replace by the dropdown option values and you can replace the html_options for the width.
eg. <% select("company", "branch_id", Branch.all.collect {|b| [ b.name, b.id ] }, { :prompt => "Select" }, {:class => "companySelect" })
For select_tag you can use
select_tag(name, option_tags = nil, options = {})
Here the option is similar to html_options of select.
eg. <%= select_tag 'company_name', options_for_select(get_company_name), :class => "select1"%>
For more details please see select Tag and select
Solution 2
In gist, I use:
<%= f.select(:my_select_name, [1,2,3,4,5], {}, :style => "width:70px") %>
Or if I am using something like Twitter Bootstrap, I use a class:
<%= f.select(:my_select_name, [1,2,3,4,5], {}, :class => "col-md-1") %>
Misha Moroshko
I build products that make humans happier. Previously Front End engineer at Facebook. Now, reimagining live experiences at https://muso.live
Updated on August 15, 2020Comments
-
Misha Moroshko almost 4 years
I create the select box like this:
f.select(:my_select_name, options_for_select(...))
How could I control the size (width) of the select box ?
For input text field I do:
f.text_field(:field_name, :size => my_size)
but for "select" it doesn't work.
Please advise.
-
Misha Moroshko over 13 yearsHi! Where can I see all the available options for
html_options
andoptions
? -
ssri over 13 yearsThe commonly used html_options are :multiple - allow multiple choices, :disabled - disable the input, :size - set the size, :class - define the class, :onclick - calls javascript onclick and other key creates standard HTML attributes. For the options you can check api.rubyonrails.org/classes/ActionView/Helpers/…
-
Misha Moroshko over 13 yearsThanks, but I still don't understand how to set the size of the select box.
:size
does not work forselect
(only for text fields). Could you please elaborate ? -
ssri over 13 yearsIf you provide the option size for a select box it will take that as a vertical size, for width you can use <%= select_tag 'company_name', options_for_select(get_company_name), :class => "select1"%> and providing width to the class select1 in the css or you can use <%= select_tag 'company_name', options_for_select(get_company_name), :style => 'width: 500px;'%>
-
Misha Moroshko over 13 yearsNow I understand! Thanks a lot!!
-
ksugiarto about 11 yearsThanks, so work for me. You can also do like this
<%= f.select(:foo_id, Foo.all.collect{|foo| [foo.name, foo.id,]}, {}, :style => "width:250px")