0

I need help!

I need that, after the user submits the form below, the email is validated, an alert is displayed and changes a part of the screen with the message "Welcome + email" for at least 5sec.

<form name="formcontact1" action="#">
    <input type='text' name='email' size="36" placeholder="Your e-mail :)"/>
    <input type="submit" name="submit" value="SUBMIT" onclick="ValidateEmail(document.formcontact1.email)" />
</form>

I have the following script to validate email that is working perfect!

function ValidateEmail(inputText) {

  var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  if (inputText.value.match(mailformat)) {
    alert("Email " + inputText.value + " has been sent");
    document.getElementById('title1').innerHTML = 'Welcome ' + inputText.value;
    return true;

  }
  else {
    alert("Invalid Email");
    document.formcontact1.email.focus();
    return false;
  }

}

After the button is clicked it shows the alert message "EMAIL xxx HAS BEEN SENT" (correct).

I need that it update part of the page with a message "WELCOME xxxxx".

The problem is after the alert message be shown. It update part of the page but reload. Is there a way to avoid this and keep 5 seconds before reload?. THANKS !!!

2 Answers2

2

If I understand you correctly you want to use preventDefault() which stops the default behaviour of refreshing the page on form submit function https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

And then use setTimeout()-function to wait x amount of seconds.

<form name="formcontact1" action="#">
    <input type='text' name='email' size="36" placeholder="Your e-mail :)"/>
    <input type="submit" name="submit" value="SUBMIT" onclick="ValidateEmail(event, document.formcontact1.email)" />
</form>

ValidateEmail(event, inputText) {
event.preventDefault();


  var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  if (inputText.value.match(mailformat)) {
    alert("Email " + inputText.value + " has been sent");
    document.getElementById('title1').innerHTML = 'Welcome ' + inputText.value;
    return true;

  }
  else {
    alert("Invalid Email");
    document.formcontact1.email.focus();
    return false;
  }

}
DoobyScooby
  • 367
  • 3
  • 6
  • 17
0

If you don't want the browser to call submit event's built-in handler (which reloads the page), you'll need to return false in successful check branch as well. Then add setTimeout call there right before returning false that will reload the page using window.location.reload() after a delay.

UPD: The handler part would look like this:

if (inputText.value.match(mailformat)) {
    alert("Email " + inputText.value + " has been sent");
    document.getElementById('title1').innerHTML = 'Welcome ' + inputText.value;
    setTimeout(function() {location.reload();}, 5000);
}
else {
 // same as before
}
return false; // for both branches
Ivan Kashtanov
  • 674
  • 4
  • 17