Home > Software design >  Why does alert() execute before my $.each loop?
Why does alert() execute before my $.each loop?

Time:02-03

I'm using the jQuery validation plugin with a fairly large form (88 fields) that was converted to html5 from a fillable PDF by this nice online tool. It works great, but seems to be acting more asynchronously than I want it to.

In the code that runs in response to clicking the Submit button for the form, if any validation errors were detected, I want to display the messages and pop up an alert telling the user to correct the errors shown and try again. The code looks like this:

        success: function() {
            const OSHform=$("form").eq(0);
            if (OSHform.valid()) {
                top.document.location.href = "/Adsentry/completed";
            }
            else {
                OSH.placeMessages();
                alert("Fields did not validate. Please fix the highlighted fields and try again");
            }
        }

Where:

OSH.placeMessages = function() {
    $('div[id^="form"].error').each(function(index) {
        let me = $( this )
        let labelid = me.attr("id");
        let inputid = labelid.replace("-error", "");
        let input_elem = $("#"   inputid);
        let heightnum = 1 * input_elem.css("height").replace("px", "");
        let topnum = 1 * input_elem.css("top").replace("px","");
        if (input_elem.attr("name") === "JR DOB") {
            topnum -= heightnum;
        }
        let leftnum = 1 * input_elem.css("left").replace("px", "");
        let widthnum = 1 * input_elem.css("width").replace("px", "");
        me.css("position", "absolute");
        me.css("top", (topnum   heightnum - 6)   "px");
        me.css("left", (leftnum   10)   "px");
        me.css("color", "red");
        me.css("z-index", 1000);
        me.css("display", "block");
    });
}

But when I submit a form with validation errors, the alert pops up first, before any errors are displayed in the form. Then when I click OK to dismiss the alert, the invalid fields get highlighted and error messages get filled in, just as they should. How can I make the alert wait until after the messages are displayed? I didn't expect that the $.each() loop would go off to async land and let the alert() run ahead on the main thread...

Of course the real question is how do I get it to behave the way I expect? It doesn't seem like $.each returns a promise such that I could put the alert() in a function called when the promise is resolved...

CodePudding user response:

You can use setTimeout to allow the browser to repaint first.

setTimeout(()=>alert("Fields did not validate. Please fix the highlighted fields and try again"));
  • Related