My Rails 3.2.13 app uses a checkbox array (multiple possible values for same field name), with labels:
%table
%tr
%td
= check_box_tag 'fruits[]', 'apple'
%td
= label_tag 'fruits[apple]', 'I like Apples'
%tr
%td
= check_box_tag 'fruits[]', 'banana'
%td
= label_tag 'fruits[banana]', 'I like Bananas'
The form correctly submit the checkbox in params as params[:fruits] => ['apple', 'banana']
But the labels are broken - clicking the labels does nothing. (Because the html label tag's for = 'fruits_xxxx' but the ID of all the checkboxes is just id = 'fruits_' so the label doesn't associate with the checkbox.)
How do I specify the label_tag in such a way that it correctly associates with its check_box_tag? (I also tried using a :value for the label tag eg = label_tag 'fruits[]', I like Apples', :value => 'apple'
but that did not work either)
Note: the closest I've come is using the block format for label tag (putting the checkbox within the label) like below the label works, BUT, using the block structure prevents putting the checkbox and label in separate cells:
= label_tag do
= check_box_tag 'fruits[]', 'apple'
I like Apples
= label_tag do
= check_box_tag 'fruits[]', 'banana'
I like Bananas
You can pass checkbox attributes to check_box_tag method as fourth argument. In this case you need to set id equal to label's "for" attribute.
%td
= check_box_tag 'fruits[]', 'apple', params[:fruits] && params[:fruits].include?('apple'), :id => 'fruits_apple'
%td
= label_tag 'fruits_apple', 'I like Apples'
If someone went here by googling here is a more right answer if you are using form_for
:
%td
= f.check_box :fruits, { multiple: true }, 'apple'
%td
= f.label :fruits, 'I like Apples', value: 'apple'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With