Home > Software engineering >  Use addEventListener() to access multiple objects
Use addEventListener() to access multiple objects

Time:01-06

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

CodePudding user response:

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"/>
<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.

Sidenote: The hidden attribute is not supported on <input> elements. You do have a type="hidden", but that disables the checkbox type. You'll have to hide the input with CSS. See all supported attributes.

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 */
}
  •  Tags:  
  • Related