Color background of label with for attribute only when checkbox is checked CSS

78 Views Asked by At

There are a lot of examples of coloring All labels when a check box is checked. I need to color just a single label with a "for" attribute

I am trying:

input[type="checkbox"]:checked~label[for=Sign_me_up_for_the_newsletter_and_periodic_alerts] {
  background: green !important;
}
<div class="pull-right">
  <label for="Sign_me_up_for_the_newsletter_and_periodic_alerts">Sign me up for the newsletter and periodic alerts</label>
  <input type="checkbox" name="newsletter_optin" id="newsletter_optin" value="yes" class="newsletter_optin">
  <br>
  <label class="text-danger" for="I_Agree_to_the_Terms_of_Agreement">I agree to the terms of agreement</label>
  <input type="checkbox" name="terms_of_agreement" id="terms_of_agreement" value="yes" class="accept_tos">
</div>

When I check the checkbox, nothing happens

2

There are 2 best solutions below

1
On BEST ANSWER

It can be done with CSS :has() selector.

Note, I edited your markup a little, so values of a pair of for= and id= are matched.

label:has(+ input[type="checkbox"]:checked) {
  color: green;
}
<div class="pull-right">
  <label for="newsletter_optin">Sign me up for the newsletter and periodic alerts</label>
  <input type="checkbox" name="newsletter_optin" id="newsletter_optin" value="yes" class="newsletter_optin">
  <br>
  <label class="text-danger" for="terms_of_agreement">I agree to the terms of agreement</label>
  <input type="checkbox" name="terms_of_agreement" id="terms_of_agreement" value="yes" class="accept_tos">
</div>

1
On

One possible solution is to use JavaScript to add a class to the label when the checkbox is checked. Here's how you can do it:

<style>
  /* Define the style for the highlighted label */
  .highlight-label {
    color: green !important;
  }
</style>

<div class="pull-right">
  <!-- Use a unique ID for the label -->
  <label for="newsletter_optin" id="newsletter_label">Sign me up for the newsletter and periodic alerts</label>
  <input type="checkbox" name="newsletter_optin" id="newsletter_optin" value="yes" class="newsletter_optin">
  <br>
  <label class="text-danger" for="I_Agree_to_the_Terms_of_Agreement">I agree to the terms of agreement</label>
  <input type="checkbox" name="terms_of_agreement" id="terms_of_agreement" value="yes" class="accept_tos">
</div>

<script>
  // Get the checkbox and label elements
  const checkbox = document.getElementById('newsletter_optin');
  const label = document.getElementById('newsletter_label');

  // Add event listener to the checkbox
  checkbox.addEventListener('change', function() {
    // If checkbox is checked, add the 'highlight-label' class to the label; otherwise, remove the class
    if (this.checked) {
      label.classList.add('highlight-label');
    } else {
      label.classList.remove('highlight-label');
    }
  });
</script>