JQuery delayed with .each ()

Any ideas on how you can use deferred jQuery methods with a function that detects all modified forms and sends each one as an Ajax record?

I can make the same work if I just list the loading of forms, but if I use ...

$('form.changed').each(function(){ return $(this).submitWithAjax(); }); 

A more complete version of the code I'm trying to get is here ... in JS Fiddle

Thanks in advance!

+7
source share
2 answers

Instead of ".each ()" use ".map ()":

 var deferreds = $('form.changed').map(function(i, elem) { return $(this).submitWithAjax(); }); $.when.apply(null, deferreds.get()).then(function() { ... }); 

"$ .when ()" allows you to combine a bunch of pending objects and wait until all of them succeed (or for any failure, note the difference). Usually this allows an arbitrary number of arguments, but since we have an array, I used "apply ()".

Note that I only used this stuff lightly, so read the jQuery API docs to double check :-) edit - also, while re-reading my question, I may have misunderstood you.

+17
source

Delegating change events to form fields can solve your problem here.

 $('form').delegate('input[type=text], input[type=radio], select', 'change', function(evt){ // your submits here console.log('changed!') }); 
0
source

All Articles