Rails checkbox selectable area
Right no开发者_如何学编程w my rails checkboxes are only toggled if you click on the checkbox; nothing happens if I click the text associated with the checkbox. Is there a way to get the checkbox to toggle if you click the TEXT as well?
<% @books.each do |b| %>
<%= check_box_tag "books[]", b.book %><%= b.book %><br />
<% end %>
This was tricky because of the [] that are needed to work with checkbox collections. Just do the following:
View:
<% @books.each do |b| %> <%= check_box_tag "books[#{b.id}]", b.book %> <%= label_tag "books[#{b.id}]", b.book %> <br /> <% end %>
Then in the controller access the parameter by it's values
. Otherwise it looks like 135=>Book1. Use values
to get just Book1
params[:books].values
Or an even easier way is to simply wrap the check_box_tag
with a <label>
like so:
...
<label><%= check_box_tag "books[]", b.book %></label>
...
Notice now you don't even need to worry about the unique id via #{b.id}
so the controller code can be changed back to
params[:books] # notice the .values is removed
You need to put the text in a label tag which points at the ID of the checkbox. Rails has a label helper for it.
精彩评论