0

When I finish validating the form, I want to show a success message but it automatically refreshes and does not allow time to see anything. I'm using bootstrap 4.1.3

This is my portion code:

<div class="container">
<div class="py-5 text-center">
    <h2>Inscription 2019</h2>
    <div id="alertOk" class="alert alert-success d-none"  role="alert">
      Success!
    </div>
</div>

<div class="col-md-12 order-md-1">
  <h5 class="mb-3">* Especialidad</h5>
  <form id="inscriptoForm" class="needs-validation" novalidate>
    <div class="row">
      <div class="col-md-4 mb-3">
        <label for="firstName">* Name</label>
        <input type="text" class="form-control" id="name" name="name" required>
        <div class="invalid-feedback">
          Name is required.
        </div>
      </div>
</div>

<script type='text/javascript'>
(function() {
  'use strict';
   window.addEventListener('load', function() {
    var forms = document.getElementsByClassName('needs-validation');
    var validation = Array.prototype.filter.call(forms, function(form) {
  form.addEventListener('submit', function(event) {
    if (form.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
    } else {
        $('#alertOk').removeClass('d-none'); //remove class to show message.
    }   
   }, false);
  });
 }, false); 
})(); 

The validation works but when you click on the submit, it shows the message very quickly and can not be read. Return the blank form.

GAL
  • 39
  • 1
  • 8

1 Answers1

1

There are two scenarios:

  1. You can show the success message before refreshing the page
  2. You can show the success message after sending the form (after page refresh)

For the first scenario, all you have to do is debounce the submit event.

const TIME_FOR_ALERT_OK_MESSAGE = 2000; // two seconds

form.addEventListener('submit', function(event) {
  event.preventDefault();
  event.stopPropagation();

  if (form.checkValidity()) {
    $('#alertOk').removeClass('d-none'); //remove class to show message.

    setTimeout(() => {
      this.submit();
    }, TIME_FOR_ALERT_OK_MESSAGE);
  }
});

You can still improve this code by cleaning the timeout and so on...

The second scenario would require some more logic, during the validation you can store some data for example in Session Storage and during the next page load base on those information render the message and hide it in a timeout as well.

Let me know which one you need if the second one I can give you more hints.

Nubzor
  • 522
  • 1
  • 5
  • 14