I'm trying to change the background color of a div with a checkbox in it. I've made this / for reference. I'm trying to replace the parent div with the 'highlight' div, so i thought the toggle div would work. When the checkbox is deselected, I would like the background color to go back to normal (or remove the 'highlight' div). Any help is appreciated.
I'm trying to change the background color of a div with a checkbox in it. I've made this http://jsfiddle/B7P65/ for reference. I'm trying to replace the parent div with the 'highlight' div, so i thought the toggle div would work. When the checkbox is deselected, I would like the background color to go back to normal (or remove the 'highlight' div). Any help is appreciated.
Share Improve this question asked Jul 10, 2012 at 23:24 VikramVikram 3493 gold badges7 silver badges16 bronze badges4 Answers
Reset to default 3You are using the parent() method incorrectly. You want to extract the toggleClass()
method from within the parent()
method and place it separately.
Try the following update:
$(this).parent().toggleClass("highlight");
Complete:
$("input:checkbox").click(function() {
var actualTime = "";
$(this).parent().toggleClass("highlight");
});
Demo: http://jsfiddle/Hmq65/
Working Demo http://jsfiddle/q3NN2/ or ANother way http://jsfiddle/KUhFp/
second demo shows how to use using .is(':checked')
just something extra if you want to use the is checked logic, :)
code
$("input:checkbox").click(function() {
var actualTime = "";
$(this).parent().toggleClass("highlight");
});
code
$("input:checkbox").click(function() {
var actualTime = "";
if ($(this).is(':checked')) {
$(this).parent().addClass("highlight");
} else {
$(this).parent().removeClass("highlight");
}
});
Try this: http://jsfiddle/B7P65/1/
This code works for highlighting when checked and remove class when unchecked.
JavaScript:
$('#your table id tr')
.filter(':has(:checkbox:checked)')
.addClass('highlight')
.end()
.click(function(event) {
$(this).toggleClass('highlight');
if (event.target.type !== 'checkbox') {
$(':checkbox', this).attr('checked', function() {
return !this.checked;
});
}
});
CSS:
.highlight{
background-color:green;
}