Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use radio button correctly in rails?

I'm trying to create some radio buttons and I'm not sure how to. Following this question I've got it set up working almost correct, but I'm new to this and not sure why I can't figure it out completely. So what I'm doing is putting a label to group the boolean and then have radio buttons which are labeled Yes and No. If the user clicks the label of Yes it should select the radio button yes (right now they can only click the button itself). This is my code as follows:

  <div class="field">
    <%= f.label :autolyse %><br />
    <%= f.label :autolyse, "Yes", :value => "Yes"  %>
    <%= f.radio_button :autolyse, true%>
    <%= f.label :autolyse, "No", :value => "No" %>
    <%= f.radio_button :autolyse, false, :checked => true %>
  </div>

The first label is for the group, it labels the group "Autolyse". Then I want a Label for "Yes", which if selected will will set true, and then obviously the next one is for False. How do I get this set up correctly?

like image 925
GiH Avatar asked Feb 25 '13 04:02

GiH


2 Answers

see label(object_name, method, content_or_options = nil, options = nil, &block)

  <div class="field">
    <%= f.label :autolyse %><br />
    <%= f.label :autolyse, "Yes", value: "true"  %>
    <%= f.radio_button :autolyse, true %>
    <%= f.label :autolyse, "No", value: "false" %>
    <%= f.radio_button :autolyse, false, checked: true %>
  </div>
like image 143
shweta Avatar answered Oct 05 '22 04:10

shweta


If you want to keep selected the option chosen by the user, you should validate the param, would be something like this:

<div class="field">
  <%= f.label :autolyse %><br />
  <%= f.label :autolyse, "Yes", :value => "true"  %>
  <%= f.radio_button :autolyse, true, !!params[:autolyse] %>
  <%= f.label :autolyse, "No", :value => "false" %>
  <%= f.radio_button :autolyse, false, !!params[:autolyse] %>
</div>

If you want to do it from the object properties you just replace the params variable for the object property:

<div class="field">
  <%= f.label :autolyse %><br />
  <%= f.label :autolyse, "Yes", :value => "true"  %>
  <%= f.radio_button :autolyse, true, [email protected] %>
  <%= f.label :autolyse, "No", :value => "false" %>
  <%= f.radio_button :autolyse, false, [email protected] %>
</div>
like image 42
Carlos Castillo Avatar answered Oct 05 '22 04:10

Carlos Castillo