Kevin Meredith Kevin Meredith - 4 months ago 12
CoffeeScript Question

Picking up Changed Checkbox from Programmatic Check/Uncheck

Given:

HTML



<input id='a' value='bbb' type='checkbox'>
<button id='btn'>
click to change checkbox
</button>


Coffeescript



$('#a').change ->
console.log 'asdfasdf'

$('#btn').click ->
document.getElementById('a').checked=true
document.getElementById('a').checked=false
document.getElementById('a').checked=true


I expected to see 3 console output log messages when I first pressed the button. But I saw none.

How can I modify my
on change
function to log a message when the
checked
status changes of my checkbox?

Answer

Because changing value or property programmatically doesn't trigger user events and if you need event to trigger you need to do that yourself

$('#btn').click ->
    var $a = $('#a')
    for(var i=0; i<3; i++){
         setTimeout(function(){
            $a.prop('checked', !$a[0].checked).change();
         },i*500)
   }