Reputation: 1067
I've put some jQuery together to change the highlighting on a container (default red, black on check) when a specific checkbox is checked. I feel this code could be simplified, but not sure how. Does anyone have any ideas please?
$("#container input:checkbox[id=cbTermsAndConditions]").change(function() {
if ($(this).attr("checked")) {
$('#container').addClass("containerblack");
$('#container').removeClass("containerred");
} else {
$(this).parent().addClass("containerred");
$(this).parent().removeClass("containerblack");
}
});
Thanks
Upvotes: 1
Views: 1257
Reputation: 13726
Little cleaner:
$("#container input:checkbox[id=cbTermsAndConditions]").click(function() {
var $this = $(this);
if ($this.attr("checked")) {
$('#container').toggleClass("containerblack containerred");
} else {
$this.parent().toggleClass("containerred containerblack");
}
});
Also, you could get the "checked" value with raw javascript, replacing the if statement with:
if(this.checked)
Upvotes: 1
Reputation: 3944
Use the click event as the value of checkbox does not change and you can probably use toggle class if all you are doing is adding and removing classes.
Upvotes: 1