Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 586
DobotJr Avatar asked Jun 04 '12 22:06

DobotJr


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

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

like image 131
ahren Avatar answered Nov 18 '22 18:11

ahren


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/

like image 5
VisioN Avatar answered Nov 18 '22 19:11

VisioN