0

I want my checkboxes's label to highlight when on and off (like a IRL switch) and I'm not figuring out how to reach all of them without having to make a listener for each of them (I belive there must be some way)

Checkboxes be like:

<label id="labeltest"><input id="checkboxtest" type="checkbox" name="diet" value="Egg" hidden/>Egg</label>

JS be like:

var labeltest = document.getElementById("labeltest")

labeltest.addEventListener("click", function () {
    if (this.firstChild.checked) {
        this.classList.remove("unchecked")
        this.classList.add("checked")
    } else if (this.firstChild.checked === false) {
        this.classList.remove("checked")
        this.classList.add("unchecked")
    }
});

I've tried with class instead of ID but didn't work

Also tried something like this with classes to make labeltest an array:

labeltest.forEach(element => {
    element.addEventListener("click", function () {
    (FUNCTION HERE)
});

But didn't work either

  • 2
    Though this particular case can be resolved with pure CSS, the common solution to what is asked is [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation). – Teemu Jan 05 '22 at 21:14

1 Answers1

1

You don't need any JavaScript to accomplish this.

If you reorder your input and labels like this:

<input id="diet-egg" type="checkbox" name="diet" value="Egg" hidden/>
<label for="diet-egg">Egg</label>

Important: Be sure that the for attribute value matches the id of the input the label is connected to. This enables checking and unchecking the checkbox by clicking the <label> element.

Then you can use the adjacent sibling selector + to define the styles of the label whenever the input is checked and unchecked.

input + label {
  /* unchecked label styles */
}

input:checked + label {
  /* checked label styles */
}
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
  • Thank you Emiel! That worked perfectly =) I was overcomplicating things FYI: I've tested the `hidden` as I shown above, and it still works, passes the value as bool and triggers the css also, maybe it is supported now (? idk, only tested on Chrome – martin delgado Jan 05 '22 at 21:48
  • 1
    You're welcome. Thanks for pointing that out. I checked again and `hidden` seems to fall under [global attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes) which are supported on input tags. So yeah, you can use them. – Emiel Zuurbier Jan 06 '22 at 08:29