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.
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!");
}
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With