Courtney Stephenson
Courtney Stephenson

Reputation: 930

jQuery form error iterations

I have a jQuery form that displays a message if the user doesn't fill in the form properly using this code:

if (errorList.length > 0) {
                    permitted = false;

                    //Display error message
                    $("#" + stepName + " legend").after("<div id=\"errorList\" class=\"error\"><h3>Please correct the following </h3><ul></ul></div>");
                    for (var j = 0; j < errorList.length; j++) {
                        if (errorList[j] != undefined)
                            $("#errorList ul").append("<li>" + errorList[j] + "</li>");
                    }

                }

The problem is that when the user tries to submit the form multiple times with errors, this happens:

enter image description here

How do I solve this problem?

Upvotes: 0

Views: 115

Answers (2)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Add a .empty before the iterate..

$("#errorList ul").empty();
for(var j = 0; j < errorList.length; j++) {
if (errorList[j] != undefined)
    $("#errorList ul").append("<li>" + errorList[j] + "</li>");
}

Upvotes: 3

mkoryak
mkoryak

Reputation: 57928

try:

           if (errorList.length > 0) {
                permitted = false;

                //Display error message
                $("#" + stepName + " legend").after("<div id=\"errorList\" class=\"error\"><h3>Please correct the following </h3><ul></ul></div>");
                $("#errorList ul").empty(); // THIS FIXES IT
                for (var j = 0; j < errorList.length; j++) {
                    if (errorList[j] != undefined)
                        $("#errorList ul").append("<li>" + errorList[j] + "</li>");
                }

            }

Upvotes: 2

Related Questions