A question came up in #prototype today, “How can I observe a state change (checked – on/not-checked – off) on a checkbox when the state is changed by the user (mouse click) or programmatically?”. Simple right? Just observe the change event on the checkbox and that should fire every time the value property changes. Only if it was that simple!
Checkboxes do not rely on the value property, but rather the checked property.
So what’s the best way to observe a checkbox when it’s state is changed?
Observe the click event. The click event fires after the control updates the checked property which gives you access to the current checked state (true = on, false = off).
What if you want to set the state programmatically? Can you just set the checked property to true or false?
Calling the click() method simulates a mouse click on the element which fires our click event. The click() method is only available on inputs of type button, checkbox, radio, reset or submit.
Sample Prototype Code:
<input type="checkbox" id="mycheckbox" > <br /> <button id="mybutton">click()</button> <script type="text/javascript"> document.observe('dom:loaded', function(e) { $('mycheckbox').observe('click', function(e) { alert('checked = ' + this.checked); }); $('mybutton').observe('click', function(e) { $('mycheckbox').click(); }); }); </script>
Update: After writing, kangax was so nice to lead me to Prototype Framework’s Form.Element.Observer (I feel like a newbie right now). This works perfectly to observe a checkbox’s state change.
new Form.Element.Observer('mycheckbox', 0.1, function(form, value) { alert('value = ' + value); // value will be 'on' or null });
When you observe a checkbox with the Form.Element.Observer, you can change the state in many ways:
$('mycheckbox').checked = true; $('mycheckbox').setAttribute('checked', true); $('mycheckbox').setValue(''); // will un-check/null value $('mycheckbox').setValue('anything'); // will check/on value $('mycheckbox').click(); // will toggle the checkbox
I hope this helps!
- Joe
0 Response to “Observing a checkbox state change”