Changing background color of a div when clicking on a checkmark

I have a form with several checkboxes, for example:

<div><input type='checkbox' name='groupid' value='1'>1</div>
<div><input type='checkbox' name='groupid' value='2'>2</div>
<div><input type='checkbox' name='groupid' value='3'>3</div>

What I'm trying to do is check the box, change the background color of the div, and when it is not set, remove the background color. How to do it using jquery?

thank

+5
source share
3 answers

JQuery

$("input[type='checkbox']").change(function(){
    if($(this).is(":checked")){
        $(this).parent().addClass("redBackground"); 
    }else{
        $(this).parent().removeClass("redBackground");  
    }
});

CSS

.redBackground{
    background-color: red;  
}

I would recommend using the Add / Remove class rather than directly modifying the CSS of the parent div.

DEMO: http://jsfiddle.net/uJcB7/

+11
source

One solution with direct CSS attribute:

$(":checkbox").on("change", function() {
    var that = this;
    $(this).parent().css("background-color", function() {
        return that.checked ? "#ff0000" : "";
    });
});​

DEMO: http://jsfiddle.net/YQD7c/


Another solution using toggleClass:

$(":checkbox").on("change", function() {
    $(this).parent().toggleClass("checked", this.checked);
});​

Where you define the class checkedin CSS as follows:

.checked {
    background-color: #ff0000;
}​

DEMO: http://jsfiddle.net/YQD7c/1/

+4

I know this is an old thread, but I came to search, and this answer gave me most of the way. (requires some customization for WordPress). So if someone else lands on the same page that uses WordPress, give this snapshot, they worked great for me.

Script

jQuery("input[type='checkbox']").change(function(){
if(jQuery(this).is(":checked")){
    jQuery(this).parent().addClass("greenBackground"); 
}
else{
    jQuery(this).parent().removeClass("greenBackground");  
} });

CSS

.greenBackground{
background-color: #06530e;  
color: #ffffff;}
0
source

All Articles