views:

53

answers:

2

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?

A: 

That's not the way to use the label tag. Instead use it like this:

<input type="hidden" ... /> <!-- doesn't really matter where these are -->

<label for="id_of_element">Foo</label>
<input type="checkbox" id="id_of_element" ... />

Now "Foo" acts as a label for the checkbox element, and you can click on "Foo" to check or uncheck it.

Alec
Ben
+1  A: 

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.

nfm
This is what I ended up doing, but it seemed unnecessary to provide my own :id to the checkbox just so I can use it in the label. Thanks for the info on _why_ though.
Ben Scheirman