在<label>中包装<%= f.check_box%>

Ben*_*man 14 html ruby-on-rails

我在表单上有一个复选框列表.由于CSS的结构方式,标签元素直接设置样式.这需要我将复选框嵌套在标签内.

这适用于原始HTML,如果单击标签文本,则复选框的状态会发生变化.<%= f.check_box %>但是,它不适用于rails helper,因为它首先输出隐藏的输入标记.

综上所述,

<label>
   <%= f.check_box :foo %>
   Foo
</label>
Run Code Online (Sandbox Code Playgroud)

这是我想要的输出:

<label>
    <input type="checkbox" ... /> 
    <input type="hidden" ... />
    Foo
</label>
Run Code Online (Sandbox Code Playgroud)

......但是就是Rails是给我:

<label>
    <input type="hidden" ... />
    <input type="checkbox" ... />
    Foo
</label>
Run Code Online (Sandbox Code Playgroud)

所以标签行为实际上并不起作用:(.

有没有办法解决这个问题?

Tim*_*ott 36

这对我有用:

<%= f.label :foo do %>
  <%= f.check_box :foo %>
  Foo
<% end %>
Run Code Online (Sandbox Code Playgroud)

呈现:

<label for="foo">
  <input name="foo" type="hidden" value="0">
  <input checked="checked" id="foo" name="foo" type="checkbox" value="1">
  Foo
</label>
Run Code Online (Sandbox Code Playgroud)


nfm*_*nfm 7

Rails在复选框之前生成隐藏的输入,因为它需要一种方法来知道表单是否在未选中复选框的情况下提交.订单敏感的,因为复选框会覆盖隐藏的输入(如果已选中).有关详细信息,请参阅Rails API.

您应该使用<label for="checkbox_id">而不是将复选框包装在label标签中.

  • Twitter Bootstrap正在使用这种嵌套语法. (2认同)