Sami
Sami

Reputation: 1404

Javascript form not redirecting on submit

My form is calling the following function. It works on desktop and the user is directed to the download-confirmation/failure page.

However, on mobile (tested on iOS and iPad), the user is not redirected. Can anyone shed some light?

Function

function submit_form()
{
    var email = document.getElementById("main-email-field").value

    // todo email validation
    if (email.length > 7)
    {
        window.location = '/download-confirmation'
    }
    else
    {
        window.location = '/download-failed'
    }
    return false;
}

Form

<form id="main-email-form" class="email-form" method="POST" onsubmit="submit_form()" action="https://europe-west1-hoddle-website.cloudfunctions.net/registerUser" target="hiddenFrame">
    <input id="main-email-field" class="main-email-field" type="email" name="email" placeholder="Email address">
    <button id="main-email-button" class="main-email-button">Download</button>
    <input type="hidden" id="main-referralID-field" name="referralID" value="">
    <input type="hidden" id="main-referralType-field" name="referralType" value="">
    <input type="hidden" id="main-referralUserID-field" name="referralUserID" value="">
    </form>
    
    <iframe id="hiddenFrame" class="hiddenFrame" name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>

Upvotes: 0

Views: 79

Answers (1)

mplungjan
mplungjan

Reputation: 177860

Try this combination of timeout and preventDefault

window.addEventListener("load", function() {
  document.getElementById("main-email-form").addEventListener("submit", function(e) {
    const email = document.getElementById("main-email-field").value
    // todo email validation
    console.log(email,email.length); 
    if (email.length > 7) {
      setTimeout(function() {
        console.log("Download allowed");
        // window.location = '/download-confirmation'; // uncomment after testing
      }, 2000)
    } else {
      e.preventDefault(); // stop submission
      console.log("Download failed");
      // window.location = '/download-failed'; // uncomment after testing
    }
  })
})
<form id="main-email-form" class="email-form" method="POST" action="https://europe-west1-hoddle-website.cloudfunctions.net/registerUser" target="hiddenFrame">
  <input id="main-email-field" class="main-email-field" type="email" name="email" placeholder="Email address">
  <button type="submit" id="main-email-button" class="main-email-button">Download</button>
  <input type="hidden" id="main-referralID-field" name="referralID" value="">
  <input type="hidden" id="main-referralType-field" name="referralType" value="">
  <input type="hidden" id="main-referralUserID-field" name="referralUserID" value="">
</form>

<iframe id="hiddenFrame" class="hiddenFrame" name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>

Upvotes: 1

Related Questions