Search code examples
htmlruby-on-railsinputradio-buttonsimple-form

Assigning a unique class to individual radio inputs using Simple Form


I have a pair of radio inputs that I'd like to individually add unique class to. I'm aware of using input_html {class: "example-class"} but I need both classes to be different. So for instance:

<input type="radio" class="male" value="male">
<input type="radio" class="female" value="female">

I've read through the documentation for Simple Form and multiple posts here on SO but still can't seem to find a solution. Instead answers only lead to assigning one basic class to a label and/or its children inputs. This is currently how my radio buttons are setup:

<%= f.collection_radio_buttons :gender, [['male', 'male'] ,['female', 'female']], :first, :last %> 

Solution

  • You can pass a block around like :

    <%= f.collection_radio_buttons :gender, [['male', 'male'] ,['female', 'female']], :first, :last do |b|
          b.label { b.radio_button(class: (b.value == 'male' ? 'male' : 'female' )) }
        end
    %> 
    

    Read the documentation of this method:

    .. It is also possible to customize the way the elements will be shown by giving a block to the method: