Unicornese
Unicornese

Reputation: 135

Stop jQuery insertAfter from firing multiple times

I am doing some basic validation in my web app which checks that the values of the password and confirm password fields match. If it doesn't my code adds a class to both fields with an error message when the submit button is clicked.

$("#btn_register").click(function(e){

  if( $("#confirmpassword").hasClass('has-error') &&  $("#password").hasClass('has-error') ){
      e.preventDefault();
  }

 var pass1 = $("#password").val();
 var pass2 = $("#confirmpassword").val();

  if(pass1 != pass2){
      $("#password").addClass('has-error');
      $("#confirmpassword").addClass('has-error');
       $("<p class='errorMsg'>The Password and confirm password fields do not match </p>").insertAfter("#confirmpassword");
       return false;
 }

 });

Problem is if the submit button is clicked multiple times, the message that is added using insertAfter is added multiple times. I have checked similar questions on here and tried to make it work myself but have had no luck.

What am i missing? Thanks

Upvotes: 0

Views: 404

Answers (1)

void
void

Reputation: 36703

Do

if($("p.errorMsg").length==0)
    $("<p class='errorMsg'>The Password and confirm password fields do not match </p>").insertAfter("#confirmpassword");
else 
    $("p.errorMsg").html(" Any other error if you want to display then set it as HTML ");

This will insert the p only if it has not previously insterted.

Upvotes: 2

Related Questions