Search code examples
javascripthtmlwaitshow-hide

want text to display when submit input is pressed and 3 seconds later it redirects to Index.html


Need this site to show some text when the submit input is pressed and when the text shows then a timer starts (3 seconds) to then go back to ../index.html

HTML

<label for="fname">Fornavn</label>
<input type="text" id="fname" name="firstname" placeholder="Ditt fornavn.." required>

<label for="lname">Etternavn</label>
<input type="text" id="lname" name="lastname" placeholder="Ditt etternavn.." required>

<label for="country">Fylke</label>
<select id="country" name="country">
  <option value="australia">Agder</option>
  <option value="canada">Rogaland</option>
  <option value="usa">Viken</option>
</select>

<label for="subject">Tema</label>
<textarea id="subject" name="subject" placeholder="Hva gjelder det.." style="height:200px" required></textarea>

<input id="submitNew" type="submit" value="Send inn">
</form>
</div>
</div>
<div id="success" hidden> 
  <p><center><strong>Vellykket</strong></center>Du har Vellykket Sendt inn</p>
</div>

Javascript

    function myFunction1() {
  var x = document.getElementById("success");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
function formSubmit(form) {
    document.getElementById("submitNew").value = "Loading...";
    setTimeout(function() {
        form.submit();
    }, 3000);  // 3 seconds
    return false;
}

want success text to display when submit button is pressed and 3 seconds later it redirects to Index.html enter image description here


Solution

  • First wrap your code in a form tag with an id and action="index.html"

    <form id="form1" action="index.html">
    <!-- your html fields and buttons here -->
    </form>
    

    Then, in your script, assign form to a variable and add a listener for the submit.

    Note that e.preventDefault() will avoid your form to submit immediately, then call your function to display the message and setTimeout to submit.

    var form = document.getElementById('form1');
    
    // Adds a listener for the "submit" event.
    form.addEventListener('submit', function(e) {
    
      e.preventDefault();
      document.getElementById("submitNew").value = "Loading...";
      myFunction1();
      setTimeout(function() {
          form.submit();
      }, 3000);  // 3 seconds
      return false;
    
    });