Search code examples
javascriptjqueryangularjsbindingbourbon

What, if anything, is jQuery's change method doing here?


I'm familiar with attaching a handler to a checkbox's property change like this:

$(function(){
  $("#chkbox").change(function(){
   alert($(this).val()) 
  });
});

However, doing this $("#chkbox").change(); will fire my alert, but the state of the checkbox won't actually change, which tells me that jQuery is just firing off handlers that it's already bound to an element. What is the use of calling it like [bourbon.io][1] does to close its modal?

$(".modal-fade-screen, .modal-close").on("click", function() {
  $(".modal-state:checked").prop("checked", false).change();
});

If I omit the .change() at the end, the modal still closes and it seems everything works fine. What is the use of chaining change()? I ask, because I am trying to use Angular with this modal, and I need to invoke closing the checkbox's state so I can close the modal with some other buttons. angular.element(".modal-state:checked").prop("checked", false); seems to work fine, but since I'm not aware of anything like change in Angular (it doesn't exist in jQlite), I want to be certain I'm not missing anything.


Solution

  • If you attach an change event listener to an element, every time a user triggers that event the event handler will fire. However, if you programmatically manipulate the element with change that would normally fire the event handler, the event handler would not fire. Therefore, you want trigger the change event manually once you made the change so that the event handler can be triggered.

    $(".modal-state:checked").prop("checked", false).change();
    //or $(".modal-state:checked").prop("checked", false).trigger('change');
    

    What is the use of chaining change()? It all depends on what the change event handler does.