Add custom CSS to input labels using association checkboxes

93 views
Skip to first unread message

Dan Weaver

unread,
Jun 18, 2015, 9:28:59 PM6/18/15
to plataformate...@googlegroups.com
I'm using the 'association as checkboxes' method and I'd like to add a custom CSS class to each of the checkbox input labels but I can't figure out how to target it.

Code:

<%= f.association :teachers, collection: @teachers, as: :check_boxes %>

produces the HTML I need:

<div class="input check_boxes optional">
 
<label class="check_boxes optional control-label">Teachers</label>
 
<label class="checkbox"> <!-- I want to add a class to each of these <label> elements -->
   
<input class="check_boxes optional" id="..." name="..." type="checkbox" value="..." />Teacher One
 
</label>
 
<label class="checkbox">
   
<input class="check_boxes optional" id="..." name="..." type="checkbox" value="..." />Teacher Two
 
</label>
 
<label class="checkbox">
   
<input class="check_boxes optional" id="..." name="..." type="checkbox" value="..." />Teacher Three
 
</label>
 
<label class="checkbox">
   
<input class="check_boxes optional" id="..." name="..." type="checkbox" value="..." />Teacher Four
 
</label>
 
<input name="..." type="hidden" value="" />
</div>

Now I'd like to add a CSS class to each of the label elements to lay them out using my grid system.

I can't target them using:

label_html: { class: 'column_3' }

because this targets the label for the whole section. I'm actually removing this label (not shown above) using:

label: false

so any other references to it are redundant.

I've tried several methods of targeting the element and none of them work:

input_label_html: { class:'column_3' }
input_label_class
: 'column_3'
label_class
:
'column_3'
label_html
:{ class:'column_3' } #error: key not found

I can add a custom CSS class to the <input> element using:

input_html: { class: 'column_3' }

but that doesn't work with my grid system, it needs to be the parent <label> element for each input.

Is there a key I can use to solve this?

Cédric Lor

unread,
Jul 5, 2015, 5:02:32 AM7/5/15
to plataformate...@googlegroups.com
Hello,

Have you tried setting values for item_wrapper_tag (to a span, for instance) and item_wrapper_class?

Let's say:
item_wrapper_tag: "span",
item_wrapper_class: "my-wrapper-class"

It would not add the class to the label but to the wrapper (including the label) of a given item. Then in you css, you can do:
 
span.my-wrapper-class > label.checkbox {
  
}

Cédric Lor

unread,
Jul 7, 2015, 9:50:28 AM7/7/15
to plataformate...@googlegroups.com
HI Dan

There is even a better. There is an undocumented key called item_label_class which allows you to do exactly what you are looking for.

Regards

Cédric

Dan Weaver

unread,
Jul 7, 2015, 6:46:52 PM7/7/15
to plataformate...@googlegroups.com
Thanks a lot Cédric, that's perfect!
Reply all
Reply to author
Forward
0 new messages