1

I'm currently building a form that has checkboxes wrapped inside of labels. We are doing this because we need to swap our the original checkbox for an image. However, when the checkbox is checked, we need to make the label have a border to give some user feedback.

Here is the setup of the labels/checkboxes

<div class="one_column">
    <label for="fieldname2_1_cb0">
      <input name="fieldname2_1[]" id="fieldname2_1_cb0" class="field depItem group  required" value="Alloy Wheel(s)" vt="Alloy Wheel(s)" type="checkbox"> <span>Alloy Wheel(s)</span>
    </label>
</div>

We have tried going about is using the following but obviously doesn't work

label input[type="checkbox"]:checked + label {
border: 5px solid blue;
}

Any help would be appreciated!

I have managed to the the first checkbox using the code supplied below

    window.onload=function() {
  document.querySelector('input[type="checkbox"]').addEventListener('change', 
  function() {
      if (this.checked) {
      this.parentNode.classList.add('border-blue');
      } else {
        this.parentNode.classList.remove('border-blue');
      }
   })}

However, it only changes the first checkbox... there are 10 in total all following the same structure as above

Chris Ware
  • 105
  • 1
  • 7
  • Use `querySelectorAll` and `forEach` to iterate through the returned collection, adding the event listener to each in turn. – Heretic Monkey Feb 26 '20 at 17:54
  • Does this answer your question? [How to addeventlistener to multiple elements in a single line](https://stackoverflow.com/questions/40956717/how-to-addeventlistener-to-multiple-elements-in-a-single-line) – Heretic Monkey Feb 26 '20 at 17:56

1 Answers1

2

Using CSS, there is no way to select parent elements from child elements.

If you are allowed to use JavaScript, you can solve it this way:

document.querySelectorAll('input[type="checkbox"]').forEach(function(el) {
  el.addEventListener('change', function() {
    if (this.checked) {
      this.parentNode.classList.add('border-blue');
    } else {
      this.parentNode.classList.remove('border-blue');
    }
  })
})
.border-blue {
  border: 5px solid blue;
}

It will check for changes on input. If it is checked, a class will be added. Otherwise, the class will be removed.

Azametzin
  • 5,223
  • 12
  • 28
  • 46
  • I have managed to get the first checkbox to work using the code I have added to the question, however, it only changes the first checkbox and not the others. There is 10 checkboxes that all follow the same structure as above, Any ideas? – Chris Ware Feb 26 '20 at 17:48
  • I edited the answer. Now it works for all the inputs on the page, – Azametzin Feb 26 '20 at 18:02