开发者

Rails checkbox selectable area

开发者 https://www.devze.com 2023-02-01 20:30 出处:网络
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 to

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号