Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping <%= f.check_box %> inside <label>

I have a list of checkboxes on a form. Due to the way the CSS is structured, the label element is styled directly. This requires me to nest the checkbox inside of the tag.

This works in raw HTML, if you click on the label text, the state of the checkbox changes. It doesn't work with the rails <%= f.check_box %> helper, however, because it outputs a hidden input tag first.

In summary,

<label>
   <%= f.check_box :foo %>
   Foo
</label>

this is the output I want:

<label>
    <input type="checkbox" ... /> 
    <input type="hidden" ... />
    Foo
</label>

...but this is what rails is giving me:

<label>
    <input type="hidden" ... />
    <input type="checkbox" ... />
    Foo
</label>

So the label behavior doesn't actually work :(.

Is there any way to get around this?

like image 843
Ben Scheirman Avatar asked May 18 '10 21:05

Ben Scheirman


2 Answers

This works for me:

<%= f.label :foo do %>
  <%= f.check_box :foo %>
  Foo
<% end %>

Renders:

<label for="foo">
  <input name="foo" type="hidden" value="0">
  <input checked="checked" id="foo" name="foo" type="checkbox" value="1">
  Foo
</label>
like image 137
Tim Scott Avatar answered Nov 13 '22 07:11

Tim Scott


Rails generates the hidden input before the checkbox because it needs a way to know whether the form was submitted with the checkbox unchecked. The order is sensitive as the checkbox overrides the hidden input if it has been checked. See the Rails API for details.

You should use <label for="checkbox_id"> rather than wrapping the checkbox in your label tag.

like image 7
nfm Avatar answered Nov 13 '22 08:11

nfm