Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails how get label_tag to work when multiple (array) check_box_tag

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
like image 966
jpw Avatar asked Dec 11 '22 14:12

jpw


2 Answers

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'
like image 79
Babur Ussenakunov Avatar answered Feb 15 '23 11:02

Babur Ussenakunov


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'
like image 30
Ildar Sh Avatar answered Feb 15 '23 10:02

Ildar Sh