How to prevent jquery from being added more than once

I have jQuery that checks if a user is entering the correct email address. Then the user can return and change their email address if it is not valid. However, my code will result in the same messege error twice, because the error continues to be added inside my div errors . How can I change this to add an error only once? I would also like to remove the error if the email variable is true . This div also contains other validation errors.

JQuery

 var email = $('#email').val(); email = validateEmail(email); if (email = "false") { $('#errors').append("<p>Please enter a valid email</p>"); } 

validateEmail will return either true or false depending on whether this message is valid.

+4
source share
6 answers
 var email = $('#email').val(); email = validateEmail(email); if (email == "false"){ $('#email_error').remove(); $('#errors').append("<p id='email_error'>Please enter a valid email</p>"); } 
+12
source

when u adds an email error, set it with the class " emailerror ",

 $('#errors').append("<p class="emailerror">Please enter a valid email</p>"); 

but before adding just remove this error with class "emailerror"

 var email = $('#email').val(); email = validateEmail(email); if (email = "false"){ $('#errors .emailerror').remove(); $('#errors').append("<p class="emailerror">Please enter a valid email</p>"); } 
+4
source

Try to clear the value before adding new information, i.e. new errors:

 $('#errors').val(''); 
+3
source

Use html() or text() to set the contents of the div errors:

 $('#errors').html("<p>Please enter a valid email</p>"); 

And so as not to display anything when email is true , add else to the if :

 if (email === "false"){ $("#errors").html("<p>Please enter a valid email</p>"); } else { $("#errors").html(""); } 

Also note that instead of = I used === . This is because using a single equal sign ( = ) will simply set the email variable to false and will not actually verify the equality.

+1
source

A more appropriate way is to remove all added code from the DOM tree:

Try :

 var email = $('#email').val(); email = validateEmail(email); if (email == "false"){ $('#email_error').parent().remove(); $('#errors').append("<p id='email_error'>Please enter a valid email</p>"); } 
0
source

all you have to do is add $('.appended').remove() right after your condition, then in the text you add use the p tag and add class="appended" this works fine

0
source

Source: https://habr.com/ru/post/1389394/


All Articles