Custom event not fired when called from $(document).ready();

1.8k Views Asked by At

I have the following code

$(document).ready(function () {

    VerifyCustomerFilter();

    $("#ToDateStor").on("DateSet", function () {
       ...
    );

   function VerifyCustomerFilter() {
     if(toDate != "")     
       $("#ToDateStor").trigger('DateSet'); //This does not work
   }
}

When the condition that I have within the function 'VerifyCustomerFilter ()' is true can not trigger the custom event I created.

But when I trigger the event within an event of my DatePicker it works perfectly: See

 $("#calTo").datepicker({
      showButtonPanel: false,
      onClose: function (dateText, inst) {
          var ToDate = $(this).val().toString();
          $('#ToDateStor').html(ToDate).trigger('DateSet'); // This works!
      }
 });

Also already tried using triggerHandler().

What should I be doing wrong?

2

There are 2 best solutions below

1
On BEST ANSWER

You are triggering your event before you bind the listener to the element, try

$(document).ready(function () {
    // add the listener
    $("#ToDateStor").on("DateSet", function () {
       ...
    });

    // define the function
    function VerifyCustomerFilter() {
        if(toDate != "")     
            $("#ToDateStor").trigger('DateSet'); //This does not work
        }
     }

     // call the function
     VerifyCustomerFilter();
});
2
On
$(document).ready(function () {

 function VerifyCustomerFilter() {
     if(toDate != "")     
       $("#ToDateStor").trigger('DateSet'); //This should work now
   }


    $("#ToDateStor").on("DateSet", function () {
       ...
    );
  //First bind the event,then call it
    VerifyCustomerFilter();

}

You were calling the function,before binding the event.