0

I want to add a class to my label of my checkbox if it's checked.

Heres my html

<ul class="checkbox-list">
    <li><label class="rounded-all">Google <input class="checkbox-row" name="google" type="checkbox" value=""></label></li>
    <li><label class="rounded-all">Bing <input class="checkbox-row" name="bing" type="checkbox" value=""></label></li>
    <li><label class="rounded-all">Facebook <input class="checkbox-row" name="facebook" type="checkbox" value=""></label> </li> 
</ul>

I tried with this piece of code i got off here but doesn't seem too do the trick:

$(".checkbox-row").change(function() {
    $(this).closest('.checkbox-list li label').toggleClass("selected", this.checked);
});

2 Answers 2

3

What you have works, you can test it here. What's likely happening is your CSS selector for your .selected class isn't specific enough, and so the properties just aren't getting applied.

For example, this may not work (if say there was a .checkbox-list li label style defined with another color):

.selected { color: red; }

While a more specific selector would:

.checkbox-list li label.selected { color: red; }

It's worth nothing though, your .closest() call can be simplified a bit using just label:

$(".checkbox-row").change(function() {
  $(this).closest('label').toggleClass("selected", this.checked);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, works well. Like you say i just had to simplify the CSS class.
2

Try this:

$(".checkbox-row").change(function() {
    if($(this).is(':checked')) 
        $(this).parent().addClass('selected'); 
    else 
        $(this).parent().removeClass('selected');
});

2 Comments

This will add the class to the <li>, not the <label>.
No it won't - Direct parent of the input is the label.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.