简体   繁体   中英

How to stop an alert message appending multiple times when using .each()

I'm using the JQuery .each() to grab all the values of a class called "required". If any of these inputs are empty I want an alert message to pop up. It all works great. However, I am not happy with the way I have done the affect on the alert. I want to use the delay() and then slideUp. However, when using the delay() I get an alert message for every pass of the each. I just want 1 alert when using the alert. I tried using appendTo() but that did not work.

What am I doing wrong ?

$(document).ready(function () {

    $("#quotation.btn").mousedown(function () {      // THIS IS THE SUBMIT BUTTON OMN THE FORM

        $(".required").each(function () {      //HERE IS THE EACH

            var required = $(this).val();  // WE GRAB THE VALUES OF THE "REQUIRED FIELDS"

            if (required == "") {                   // IF ANY OF THE REQUIRED FIELDS ARE EMPTY WE EXECUTE THE FOLLOWING:

                var message = '<p class="alert alert-danger" > You have Missed Off One or More Required Fields !</p>'

                $("#collapseOne").collapse('show');
                $("#collapseThree").collapse('hide');

                // message.appendTo($("#alertMessage")).delay(5000).slideUp(500); // THIS DOES NOT WORK !

                $("#alertMessage").append(message).slideUp(10000);  // THIS DOES WORK SO LONG AS I DO NOT USE DELAY() !

                $(this).css({"border": "solid 2px", "color": "#ff6666"})


            }

            else {
                $(this).css({"border": "1px solid #ccc", "background-image": "none"})

            }
        })
    });

});

You could simply set a variable within your conditional statement:

if (required == "") {
    showAlert = true;
}

Then outside of the each statement you could check if you need to display the alert:

if (showAlert) {
   $("#alertMessage").append(message).slideUp(10000); 
   showAlert = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM