简体   繁体   中英

How to add a class to select_tag in Ruby on Rails

Having difficulty adding a class tag to this:

 <div class="field">
    <%= label_tag(:school_or_org, "Are you a school or a non-profit organization?") %> 
    <%= select_tag(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"] ]))  %> 
  </div>

This is what I've tried, among others:

      <div class="field">
         <%= label_tag(:school_or_org, "Are you a school or a non-profit organization?") %> 
         <%= select_tag(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"], {:class => 'form-control'} ]))  %> 
     </div> 

When I check it via firefbug, I don' see the class information, so clearly it's not being added.

How do I get it added so it shows up in the form?

Merci

Edit One

Do you mean like this:

 <%= select_tag(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"]] ), {:class => 'form-control'})  %> 

It didn't work.

Just for reference, this is what I'm trying to have the select box look like: http://getbootstrap.com/css/#forms (look at Selects section). That's where I got 'form-control' from.

If you are using the select helper , you need an empty options hash followed by your html options like so:

select(object, method, choices, options = {}, html_options = {})

With your example, that would look like this:

<%= select(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"]] ), {}, {:class => 'form-control'})  %>

If you are using the select_tag helper , you can add in the hash at the end as part of the options hash:

 select_tag(name, option_tags = nil, options = {})

This works because any options that are not recognised are passed in as standard HTML attributes.

With your example , that would look like this:

<%= select_tag(:school_or_org, options_for_select([ ['school', "school"], ['non-profit', "non-profit"]] ), {:class => 'form-control'})  %> 

If you want the class on the select box itself, then you have a parenthesis nesting error happening here. The {:class => 'form-control'} snippet needs to be outside of the parens for the options_for_select call.

If you want the class to be applied to the options then each array element needs the class declaration like so: ['non-profit', "non-profit", {:class => 'form-control'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM