How to reliably detect when a checkbox has been checked, whatever it is?

I am looking for a way to detect when a flag value has been changed. addEventListener()or jQuery on()works mostly, but changes made this way will not be detected:

<input type="checkbox" id="testCheckbox">

<!--- some other script further down the page, not under my control -->
<script type="text/javascript">
   document.getElementById("testCheckbox").checked = true;
</script>

Is there any way to detect this change? Even what works only in the latest browsers would be great.

Edit: To be clear, I want to detect changes made by any script on the page. I do not necessarily control them, so I cannot initiate the event myself.

+5
source share
4 answers

( , ), IE propertychange. , - .

: http://jsfiddle.net/X4a2N/1/

:

document.getElementById("testCheckbox").onpropertychange = function(evt) {
    evt = evt || window.event;
    if (evt.propertyName == "checked") {
        alert("Checkedness changed!");
    }
};
+4

, . Object.observe Javascript.

undefined. , change.

+4

. "" .

    Actions that invoke the CheckboxStateChange event:
          1. Changing the state of the checkbox by a mouse click.
          2. Changing the state of the checkbox with an accesskey.
          3. Changing the state of the checkbox with the SPACE key.

    Actions that do not invoke the CheckboxStateChange event:
          1. Changing the value of the checked property from script.
+2
source

There is still no way to do this without polling or using the shadow DOM infrastructure, such as React, which monitors the state. This is because changing the checkbox / radio property .checked = trueis a state change, not a DOM mutation. Here is a demonstration of this:

http://jsfiddle.net/6DHXs/1/

0
source

All Articles