consider this scenario for validating:
function validateForm (validCallback) {
$('#first-name').add($('#last-name')).add($('#address')).each(function () {
// validating fields and adding 'invalid' class to invalid fields.
});
// doing validation this way for almost 50 fields (loop over 50 fields)
if ($('#holder .invalid').length == 0) {
// submitting data here, only when all fields are validated.
}
}
Now, my problem is that, the if block get executed before loops are finished. I expected the body of validateForm
to be executed synchronously, but it seems that jQuery each()
function gets executed asynchronously. Am I right? Why this doesn't work?
For me it works like asyncronous. If it works sync, why it works like that:
jQuery
is purely a javascript library. Exceptajax
,setTimeout
andsetInterval
there is nothing that can asynchronously executed inJavaScript
. Soeach
is definitely executed synchronously. There is definitely some js error inside theeach
block code. You should take a look in the console for any errors.Alternatively you can take a look at jQuery queue to execute any function in the queue. This will make sure the queued function will be executed only when the previous code execution is complete.
Same problem. So i fix like this
The jQuery.each method loops Synchronously, but you can't guarantee that it'll loop through the items in any specific order.
Another reason to ask that question would be that .each will simply stop iteration when the (.each() ) function returns false, and an additional variable must be used to pass the "return false" information.
Thats how i do it