Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest input inside f.label ( rails form generation )

I want to use the f.label method to create my form element labels, however - i want to have the form element nested inside the label. Is this possible?

-- From W3C --

To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.

In this example, we implicitly associate two labels with two text input controls:

<form action="..." method="post">
 <p>
  <label>
     First Name
     <input type="text" name="firstname" />
  </label>
  <label>
     <input type="text" name="lastname" />
     Last Name
  </label>
  </p>
</form>
like image 717
Michael Avatar asked Mar 16 '10 18:03

Michael


2 Answers

You can nest your form helper inside of a label using a block. Here is an example using HAML, but it also works with ERB.

= form_for your_resource do |f|
  = f.label :first_name do
    = f.text_field :first_name
like image 164
Dan Garland Avatar answered Nov 11 '22 08:11

Dan Garland


As Dan Garland above mentioned previously, you can definitely nest inputs inside labels with a simple block. I'm providing this answer as an example using ERB and specifically to show exactly how you have to get Bootstrap button groups to work like radio buttons as they require this nesting. It took me a while to figure out, so hopefully this will help someone else.

For this example (Rails 4.2), the button group lets a user select between 3 different distance options:

<%= form_for(@location) do |f| %>
  <div class="field form-group">
    <%= f.label :distance %><br>
    <div class="btn-group" data-toggle="buttons">
      <%= f.label :distance, class: "btn btn-primary active" do %>
        <%= f.radio_button :distance, 0.3, checked: true %>
        0.3 miles
      <% end %>
      <%= f.label :distance, class: "btn btn-primary" do %>
        <%= f.radio_button :distance, 0.5 %>
        0.5 miles
      <% end %>
      <%= f.label :distance, class: "btn btn-primary" do %>
        <%= f.radio_button :distance, 1 %>
        1 mile
      <% end %>
    </div>
  </div>
  <div class="actions">
    <%= f.submit "Submit Location", class: "btn btn-success" %>
  </div>
<% end %>

P.S. I can't yet post screenshots to show what this looks like, but once I get enough rep points, I will.

like image 21
Sia Avatar answered Nov 11 '22 06:11

Sia