2

What is the best way to automatically check if a checkbox has been (un)checked. I know that the onclick event will catch click events but what if another script changes the state of the checkbox ala "check all button".

5 Answers 5

2

You can use the 'change' event. The behavior is buggy in IE, so you might have to observe both click and change - http://www.quirksmode.org/dom/events/change.html.

3
  • It isn't "buggy" in IE, it is implemented per the W3C HTML 4.01 specification, which says it should fire when the control loses focus if it has been modified. Unfortunately that behaviour is confusing, so most use the click event instead and use the element's checked property.
    – RobG
    Mar 29, 2011 at 5:11
  • 1
    The change event won't detect a programmatic change using something like [checkbox].checked = true/false
    – KooiInc
    Mar 29, 2011 at 6:10
  • I agree with you. if it acted the same in all browsers and detected programmatic changes, I would've used the onchange event.
    – Robert
    Mar 29, 2011 at 14:40
1

You can't use the change event to monitor for programmatic changes (changes, not originated from a click) to the checkbox. So you'll have to make up your own monitor. One way is to use setInterval for periodic checking. Something like: setInterval(checkstate,2000);. See this this jsfiddle to see an example in action.

1
  • I figured this option was going to show up. I have used onchange but it seems unpredictable across browers. I was just trying to avoid using cpu cycles to pool a checkbox.
    – Robert
    Mar 29, 2011 at 14:37
1

using the checked property and the CheckboxStateChange event. I don't know about compatibility, though.

https://developer.mozilla.org/en/XUL/checkbox

https://developer.mozilla.org/en/XUL/Events

http://www.javascriptkit.com/javatutors/radiocheck.shtml

0

You can define one global variable in java script and change its state to checked
or unchecked on click that changes the state of check box and on another script changes
the state of the check box

0

The other scripts should initiate a checkbox click in code itself. The event will bubble even if initiated from script. Here is an example if you are interested --> http://jsfiddle.net/qSRzM/1/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.