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?
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.
This is a solution I used that includes translation.
<%=
f.label(
:foo,
"#{f.check_box(:foo)} #{t('helpers.label.foo')}".html_safe
)
%>
In en.yml
en:
helpers:
label:
foo: Foo
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.
精彩评论