sgrontflix sgrontflix - 27 days ago 9
HTML Question

alert box shows up N times after clicking N times on submit button

Given this function:

function validate() {
var elements = ["firstname", "lastname", "password", "favfood", "favsport"];

document.getElementById('register').noValidate = true;
document.getElementById('register').addEventListener('submit', function(event) {
for (var i = 0; i < elements.length; i++) {
if(document.getElementById(elements[i]).hasAttribute("required")) {
if(!document.getElementById(elements[i]).checkValidity()) {
event.preventDefault();
alert('Please, fill in every required field of the form.');
break;
}
}
}
}, false);
}


And this form:

<form name="register" id="register" method="POST" action="this-file.php">
[HTML ELEMENTS TO VALIDATE]
<input type="submit" value="Register" onclick="validate()">
</form>


When I press
Register
the first time (without filling in anything), the alert box shows up just once; if I press
Register
again, the alert box shows up twice and so on. What's going on?

I'm using a custom JavaScript function to validate my form because the
required
attribute does not work on Safari.

Thank you all in advance.

Answer

Its quite straightforward, you are adding submit event listener each time whenever your hit submit button i.e. through validate function. There are two ways to handle this either register it only once or remove the added listener first and than add it.

First Way

function validate() {
   var elements = ["firstname", "lastname", "password", "favfood", "favsport"];

   document.getElementById('register').noValidate = true;
   document.getElementById('register').addEventListener('submit', function(event) {
      for (var i = 0; i < elements.length; i++) {
         if(document.getElementById(elements[i]).hasAttribute("required")) {
            if(!document.getElementById(elements[i]).checkValidity()) {
               event.preventDefault();
               alert('Please, fill in every required field of the form.');
               break;
            }
         }
      }
   }, false);
}

validate(); // call this function directly and remove it from your submit button

Second Way

function validateCallback(event) {
    var elements = ["firstname", "lastname", "password", "favfood", "favsport"];

    for (var i = 0; i < elements.length; i++) {
     if(document.getElementById(elements[i]).hasAttribute("required")) {
        if(!document.getElementById(elements[i]).checkValidity()) {
           event.preventDefault();
           alert('Please, fill in every required field of the form.');
           break;
        }
     }
  }
}

function validate() {
   document.getElementById('register').noValidate = true;
   document.getElementById('register').removeEventListener('submit', validateCallback, false);
   document.getElementById('register').addEventListener('submit', validateCallback, false);
}

and use it same as you are using currently.