mardi 2 mai 2023

How to properly listen for checkbox.checked when it is modified by scripts? [duplicate]

Question

There's a checkbox: <input type="checkbox" id="led">. I want to be notified when a certain script try to change the value led.checked. Note that I have no idea what that script might be, nor can I modify it.

My attempts

The first solution that came to my mind was led.addEventListener("change", () => {console.log(led.checked);}). However, this only works when the user clicks on the checkbox.

The second solution I tried:

var led_val = led.checked;
Object.defineProperty(led, "checked", {
    get: () => {
        return led_val;
    },
    set: (val) => {
        led_val = val;
    }
})

The script seems to be working as expected, but the appearence of the checkbox won't be updated. i.e. When led.checked = true is executed, we're notified and led.checked does return true, but the checkbox looks as if it is not checked. Also, clicking on it won't update the value led.checked.




Aucun commentaire:

Enregistrer un commentaire