mikel mikel - 1 year ago 57
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.

or jQuery
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;

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 Source

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/


document.getElementById("testCheckbox").onpropertychange = function(evt) {
    evt = evt || window.event;
    if (evt.propertyName == "checked") {
        alert("Checkedness changed!");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download