Reputation: 4049
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
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
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
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