Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
804 views
in Technique[技术] by (71.8m points)

Labels for radio buttons in rails form

My question is similar to this one but for a Rails app.

I have a form with some radio buttons, and would like to associate labels with them. The label form helper only takes a form field as a parameter, but in this case I have multiple radio buttons for a single form field. The only way I see to do it is to manually create a label, hard coding the ID that is auto generated for the radio button. Does anyone know of a better way to do it?

For example:

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

This generates something like:

<label for="message_contactmethod">Contactmethod</label>
<input checked="checked" id="message_contactmethod_email" name="message[contactmethod]" value="email" type="radio"> Email
<input id="message_contactmethod_sms" name="message[contactmethod]" value="sms" type="radio"> SMS

What I want:

<input checked="checked" id="message_contactmethod_email" name="message[contactmethod]" value="email" type="radio"><label for="message_contactmethod_email">Email</label>
<input id="message_contactmethod_sms" name="message[contactmethod]" value="sms" type="radio"> <label for="message_contactmethod_sms">SMS</label>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...