Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 298
Michael Low Avatar asked Jan 24 '13 11:01

Michael Low


Video Answer


2 Answers

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!");
    }
};
like image 136
Tim Down Avatar answered Sep 29 '22 09:09

Tim Down


I don't think there is an elegant way. There is an Object.observe proposal for future versions of Javascript.

For now you should trigger the change event as undefined suggested. You could also define a setter function that sets the value and triggers change for you.

like image 45
Matt Zeunert Avatar answered Sep 29 '22 10:09

Matt Zeunert