How to determine the completion of jquery launch events?

I am trying to fire a second event that depends on the first like this:

... $('#productFamilyId').val(data.contents.productfamily); $('#productFamilyId').trigger('change', function() { $('#productId').val(data.contents.product); $('#productId').trigger('change'); }); 

He does not wait for the completion of the first trigger before attempting to fire the second event. Can I wait for the completion of the first trigger?

+6
source share
4 answers

There is no callback for the trigger method. Additional parameters are just parameters.

http://api.jquery.com/trigger/

In fact, you are executing the code in the second function, and then passing the result as a parameter to the event handler called by the trigger. You must call the second event in the event handler for the first event if you want them to be executed sequentially.

+1
source

Perhaps you want to:

 $('#productFamilyId').trigger('change', function() { $('#productId').val(data.contents.product); setTimeout(function(){ $('#productId').trigger('change'); },1); }); 
+2
source

you can use the javascripts setTimeout () function to make the function execute at some interval.

 $('#productFamilyId').val(data.contents.productfamily); $('#productFamilyId').trigger('change', function() { setTimeout( function(){ $('#productId').val(data.contents.product); $('#productId').trigger('change'); },100); }); 
+1
source

If your event handler does not make an asynchronous call , the triggered event will be executed and finished, and then go to the next line. Jsfiddle

 $('#productFamilyId').val(data.contents.productfamily); $('#productFamilyId').trigger('change'); // Execute after change complete $('#productId').val(data.contents.product); $('#productId').trigger('change'); 

With an asynchronous call (setTimeOut, Ajax, etc.) in the event handler, you can do this: JsFiddle

Add a callback function as a parameter in the event handler:

 $("#productFamilyId").change(function(e, callback) { // Simulating ajax setTimeout(function() { if (typeof callback === "function") callback(); }, 3000); }); 

And run as follows:

 $('#productFamilyId').trigger('change', function() { $('#productId').val(data.contents.product); $('#productId').trigger('change'); }); 
+1
source

Source: https://habr.com/ru/post/920899/


All Articles