jquerycustom-eventsjquery-triggerjquery-triggerhandler

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


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?


Solution

  • 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();
    });