You are viewing limited content. For full access, please sign in.

Question

Question

Javascript to remove css class to strike through label on a Checkbox

asked on August 19, 2022

Hello, 

I'm creating a form, and we want the checkbox choices labels to have a line-through if they are unchecked and no line-through when they are checked. I have created a CSS class for the strike-through and then thought I would use JavaScript to add or remove the class depending on whether or not the box is checked. Below is my code, but I can't get it to work. The line-through stays even if the box is checked.  I would appreciate any help as I'm pretty new to JavaScript and don't know if this is possible.  

/*CSS Class for strike through*/
.strike label {
  text-decoration: line-through;
}

Java Script

$(document).ready(function(){
 $(input[type='checkbox'].each(function() {
   $(this).click(function() {
      if($(this).is(":checked")){
     $(this).removeClass('.strike');
   } else {
     $(this).addClass('.strike');
   }
   });
 });
   });

0 0

Answer

SELECTED ANSWER
replied on August 21, 2022 Show version history

You can actually do this without JavaScript using CSS only.

Add a class to your field in Advanced settings (I used strikeThrough), then you can use selectors to only apply styling to label elements that follow an unchecked input.

CSS has a :checked selector which applies based on the state of checkboxes/radio buttons, and by combining that with :not() you can effectively target the unchecked inputs.

Then, the label is the next sibling after the checkbox, so the + selector can be used to target the first label element following an unchecked input.

.strikeThrough input:not(:checked) + label {
  text-decoration: line-through;
}

Advanced settings on field

End result

Of course CSS selectors have plenty of limitations that require JavaScript to overcome, but it can still do a lot more than people usually realize.

CSS Selectors Reference (w3schools.com)

5 0
replied on August 22, 2022

Thank you Jason! This is exactly what I was looking for, I didn't realize you could put the :not() in front of it in CSS. 

 

Your help is greatly appreciated! :) 

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.