Nest input inside f.label ( rails form generation )

前端 未结 5 453
广开言路
广开言路 2020-12-28 17:22

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 --

5条回答
  •  臣服心动
    2020-12-28 18:11

    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| %>
      
    <%= f.label :distance %>
    <%= 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 %>
    <%= f.submit "Submit Location", class: "btn btn-success" %>
    <% end %>

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

提交回复
热议问题