3

In my code, I am setting a change listener on my checkboxes here

  $(".section").change(function() { 
       if($(this).is(":checked")) {
        $("." + this.id).show();
        ...

Now I am trying to do a "code-driven" click on the checkbox, and I have

  $(".secTitle").click(function(e) {
    var elem = this;
    while(elem) {
      if (elem.className && elem.className.indexOf ('DOC_SECTION') != -1) {
        var clzes = elem.className.split(" ");
        var clzIdx = 1;
        if (elem.getAttribute('closeSecClassIdx')) {
          clzIdx = parseInt(elem.getAttribute('closeSecClassIdx'));
        }
        var chk = document.getElementById(clzes[clzIdx]);
        chk.checked = false;
        alert(chk.onchange);
        //chk.changed();
        break;
      }
      else {
        elem = elem.parentNode;
      }
    }
  });

I know that I have the right element, as chk.checked = false; is working correctly. After that I'm trying to invoke the change method set earlier but my alert is showing 'undefined'.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • jQuery does not insert anything into `onchange` when you bind a event callback to it! – AP. Apr 04 '17 at 15:55
  • You have to trigger the `change` event: http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript – nikoskip Apr 04 '17 at 16:00

1 Answers1

1

You can trigger the change event by calling $(chk).change(). Below I've created a little prototype that shows binding to the change event and invoking it.

jQuery(function($) {
    // bind to the change event
    $("input").change(function() {
        console.log('change triggered!');
    });
    
    // now trigger it
    $("input").change();    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
dana
  • 17,267
  • 6
  • 64
  • 88