mikel mikel - 1 month ago 5
Javascript Question

How to reliabily detect when a checkbox has been checked, no matter how?

I'm looking for a way to detect when a checkbox checked value has been changed.

addEventListener()
or jQuery
on()
mostly work, but neither will detect a change made this way:

<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 a way I can detect this change ? Even something that only works in the latest browsers would be great.

Edit: To be clear, I want to detect changes made by any script on the page. I don't necessarily control them, so I can't trigger an event myself.

Answer

For what it's worth (not much, I'd say), you can do this in IE only using its proprietary propertychange event. In other browsers, I'm pretty certain your only option for now is polling.

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

Code:

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