DobotJr
DobotJr

Reputation: 4049

Change background color of div when checkbox is clicked

I have a form with several checkboxes, like this:

<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 when the checkbox is checked, change the background color of the div, and when it's unchecked, remove the background color. How can I do this using jquery?

Thanks

Upvotes: 6

Views: 32075

Answers (3)

duggy
duggy

Reputation: 1

I am aware that this is an old thread, but I came searching and this answer got me most of the way. (needed some tweaking for WordPress) So if someone else lands on this same page that is using WordPress, give this a shot, worked great for me.

The Script

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

The CSS

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

Upvotes: 0

VisioN
VisioN

Reputation: 145478

One solution with direct CSS attribute changing:

$(":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 class checked in CSS as follows:

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

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

Upvotes: 5

ahren
ahren

Reputation: 16959

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'd recommend using Add/Remove class, as opposed to changing the CSS of the parent div directly.

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

Upvotes: 13

Related Questions