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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With