score:7

Accepted answer

d3 is using the standard addEventListener in it's on method. The problem you have is that changing the checked property doesn't raise any events for the addEventListener to hear. The proper way would be to just call the handler yourself after setting the proptery:

var myInput = d3.select("input");
myInput.property("checked", true);
myInput.on("change")(); // call it yourself

Full working code:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
  </head>

  <body>
    <input type="checkbox" />
    <script>
      
      var checked = false;
      setInterval(function(){
        checked = !checked;
        var myInput = d3.select("input");
        myInput.property("checked", checked);
        myInput.on("change")();
      }, 2000);
      
      
      d3.select("input").on("change", function(d){
        console.log('checkbox changed');
      });

    </script>
  </body>

</html>

score:0

The solution suggested by Mark works flawlessly however just alternatively I would also like to mention that rather than calling the event handler yourself you can trigger the event yourself and leave rest of the code as it is. The onchange event is triggered on following sequence focus-valueChange-unfocus. Now this does not happen when you change it without clicking on it, the value changes but no focus. Anyway so instead of relying on that you can just trigger onchange event yourself. I created a fiddle here which explains it. Hope it helps: https://jsfiddle.net/xcjje9r3/6/

window.clickMe = function() {
  tmp = d3.select('#cbox');
  if (tmp.property('checked') == false) tmp.property('checked', true);
  else tmp.property('checked', false);
  tmp[0][0].dispatchEvent(evt); //MANUALLY TRIGGER EVENT
}
//tmp[0][0] is becoz d3.select returns an array and [0][0] position stores the actual DOM element in this array.

window.listenerInitialize = function() {
  evt = document.createEvent("HTMLEvents"); //CREATE NEW EVENT WITH TYPE
  evt.initEvent("change", false, true); //THE EXACT EVENT TO FIRE
  d3.select('#cbox').on('change', alerting); //ADDING LISTENER FOR EVENT
}

window.alerting = function() {
  alert('testEvent');
}


Related Query

More Query from same tag