Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change color of checkbox label while toggling checked/unchecked state on click

I'm trying to change the font color and background color of my checkbox label when I check or uncheck. I found a javascript solution on this site but haven't been able to make the code to work. Here is what I've tried so far. Right now it is attaching the "highlight" class to the parent div and I only want the label to change. Thanks 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;
}
like image 259
Ansh Avatar asked Dec 13 '22 00:12

Ansh


1 Answers

You can do it using just CSS:

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

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

Also, while producing the demo I've noticed a couple of issues:

  • id="option one" - the id must be only one and you cannot have spaces
  • the value of the for attribute of the label should be the id (not name) of the corresponding input; this also lets you check/ uncheck the checkbox by clicking on the label and not on the checkbox itself
like image 113
Ana Avatar answered Apr 12 '23 22:04

Ana