質問

<%= f.label :category %><br/>
<%= check_box_tag 'category[]', '1', false %>
<%= label_tag 'community', 'community', class: 'category_select', value: '1' %>
<%= check_box_tag 'category[]', '2', false %>
<%= label_tag 'food', 'food', class: 'category_select', value: '2' %>
<%= check_box_tag 'category[]', '3', false %>
<%= label_tag 'music', 'music', class: 'category_select', value: '3' %><br/>
<%= check_box_tag 'category[]', '4', false %>
<%= label_tag 'education', 'education', class: 'category_select', value: '4' %>
<%= check_box_tag 'category[]', '5', false %>
<%= label_tag 'theatre', 'theatre', class: 'category_select', value: '5' %>
<%= check_box_tag 'category[]', '6', false %>
<%= label_tag 'art', 'art', class: 'category_select', value: '6' %><br/>
<%= check_box_tag 'category[]', '7', false %>
<%= label_tag 'culture', 'culture', class: 'category_select', value: '7' %>
<%= check_box_tag 'category[]', '8', false %>
<%= label_tag 'family', 'family', class: 'category_select', value: '8' %>
<%= check_box_tag 'category[]', '9', false %>
<%= label_tag 'sports', 'sports', class: 'category_select', value: '9' %><br/>

I'd like to be able to have these options show up in my controller under a category array, so I named all the options category[]. What I'd like to accomplish, is for the label_tag and check_box_tag fields to know about each other:

<%= check_box_tag 'community', 'community', false %>
<%= label_tag 'community', 'community', class: 'category_select' %>

here, if I click on the words, the box also gets checked. I tried to accomplish this with the values on the label_tag, but it doesn't seem to work. Can this be accomplished?

役に立ちましたか?

解決

One way to do this is to add the label elements in manually (no erb), and add the checkboxes and label content as children:

<label class="category-select">
  <%= check_box_tag 'category[]', '1', false %>
  Community
</label>
...

Although that does change the structure of the html somewhat, and may have an impact on your layout/css.

他のヒント

You can also pass a block to label_tag and then next a checkbox (along with anything else you want) inside the label tag.

<%= label_tag do %>
  <%= check_box_tag 'category[]', '1', false %>
  Community
<% end %>

Relevant docs: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-label_tag

Ok, I'm pretty late to answer this. I was looking solution for same kinda problem and came up with following:

<%= label_tag "some_name", raw("#{check_box_tag('some_name')} Click label to check") %>

This would create html as follows:

<label for="some_name"><input id="some_name" name="some_name" type="checkbox" value="1"> Click label to check</label>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top