1

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

2 Answers 2

1

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I didn't know you could toggle more than one css class. I have also changed to using this.checked. Cheers.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.