Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Jquery append more than once

I have some jQuery that checks if the user inputted a correct email address. The user can then go back and change his/her email if it is not valid. However, my code will result in the same error messege twice because the error keeps getting appended inside my errors div. How can I change this to only allow the error to be appended once? I also would like to remove the error if the email variable is true. There are also other validation errors being placed in this div.

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 the email is valid.

like image 363
kirby Avatar asked Nov 30 '22 15:11

kirby


2 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>");
}
like image 92
redmoon7777 Avatar answered Dec 04 '22 13:12

redmoon7777


when u append the email error, specity it with a class "emailerror",

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

but before append, just remove that error which have 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>");
}
like image 29
Bhavesh G Avatar answered Dec 04 '22 13:12

Bhavesh G