check_box_tag with label_tag click action

Dudo picture Dudo · Apr 19, 2013 · Viewed 20.9k times · Source
<%= 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?

Answer

zkcro picture zkcro · Apr 19, 2013

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.