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
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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With