How to change flag label color when switching checked / unverified state on click

I am trying to change the font color and background color of my checkmark when I check or uncheck the box. I found a javascript solution on this site, but could not get the code to work. Here is what I have tried so far. Now it binds the "highlight" class to the parent div, and I want the label to change. Thank you for your time.

HTML

<div class="checkboxes"> <input type="checkbox" name="1" id="option one" value="orange"><label for="1" class="highlight">Orange</label> <input type="checkbox" name="2" id="option two" value="apple"><label for="1" class="highlight">Apple</label> </div> 

Javascript

 $( '.checkboxes' ).on( 'click', 'input:checkbox', function () { $( this ).parent().toggleClass( 'highlight', this.checked ); }); // end checkbox styleโ€‹ 

CSS

 .checkboxes label { font-family:Open Sans Italic; font-size: 12px; color: #666; border-radius: 20px 20px 20px 20px; background: #f0f0f0; padding: 3px 10px; text-align: left; } .highlight { font-family:Open Sans Italic; font-size: 12px; color: white; border-radius: 20px 20px 20px 20px; background: #86b3c1; padding: 3px 10px; text-align: left; } 
+4
source share
3 answers

A label appears after the checkbox, your code seems to be for the shortcut that wraps the checkbox, for example:

 <label for="1" class="highlight">Orange <input type="checkbox" name="1" id="option one" value="orange"> </label> 

Modify html or change JS to target the next element, not the nearest parent:

 $( '.checkboxes' ).on( 'click', 'input[type="checkbox"]', function () { $( this ).next('label').toggleClass( 'highlight', this.checked ); }); 

Also, your CSS is wrong, and targeting the label will directly depend on the selection class, so it will never change color, even if the class is applied.

Here is the fiddle, I fixed it, being more specific when I targeted the highligth class:

Fiddle

And Ramson is right, you have to check the box with brackets and type = "".

+3
source

You can do this using only CSS:

 input[type=checkbox]:checked + label { /* styles that get changed */ } 

demo http://dabblet.com/gist/3157721

In addition, when creating the demo, I noticed a couple of problems:

  • id="option one" - the identifier should be only one, and you cannot have spaces
  • the value of the for label attribute must be the id (not name ) of the corresponding input ; it also allows you to check / uncheck the box by clicking on the label, rather than the flag.
+8
source

closest() cannot find the closest element to the selected element. it finds the closest parent, you can use the next() method, try the following:

Get the first element that matches the selector, starting from the current element and evolving through the DOM tree.

 $('.checkboxes').on('click', 'input[type="checkbox"]', function () { $(this).next('label').toggleClass('highlight', this.checked); }); 

note that :checkbox selector deprecated .

+2
source

All Articles