Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labels for radio buttons in rails form

People also ask

How do you label a group of radio buttons?

Radio buttons Radio button groups should always be grouped using <fieldset> .

How do you style a radio button label?

Just use label:focus-within {} to style a label with a checked radio or checkbox. Show activity on this post. As TimStieffenhofer mentioned in their answer, the easiest way is to have the input field as a child of the label and use the :focus-within pseudo-class on the label.

How do you name a radio button?

To label a radio button, add a <label> element after the <input> element and insert a for attribute with the same value as the id of the associated <input> element. Then, write your label text in the <label> tag. While using <label> isn't strictly necessary, it's considered a best practice for two reasons.

What is the tag for radio button?

The <input type="radio"> defines a radio button.


Passing the :value option to f.label will ensure the label tag's for attribute is the same as the id of the corresponding radio_button

<%= form_for(@message) do |f| %>
  <%= f.radio_button :contactmethod, 'email' %> 
  <%= f.label :contactmethod, 'Email', :value => 'email' %>
  <%= f.radio_button :contactmethod, 'sms' %>
  <%= f.label :contactmethod, 'SMS', :value => 'sms' %>
<% end %>

See ActionView::Helpers::FormHelper#label

the :value option, which is designed to target labels for radio_button tags


<% form_for(@message) do |f| %>
  <%= f.radio_button :contactmethod, 'email', :checked => true %> 
  <%= label :contactmethod_email, 'Email' %>
  <%= f.radio_button :contactmethod, 'sms' %>
  <%= label :contactmethod_sms, 'SMS' %>
<% end %>

If you want the object_name prefixed to any ID you should call form helpers on the form object:

- form_for(@message) do |f|
  = f.label :email

This also makes sure any submitted data is stored in memory should there be any validation errors etc.

If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:

= radio_button_tag "#{f.object_name}[email]", @message.email

In this case you'd need to specify the value manually to preserve any submissions.