Search code examples
javascripthtmlforms

Button's onClick function does not call window.location when the form input fields have values


function register() {
  var email = document.getElementById("emailData2").value;
  var password = document.getElementById("passwordData2").value;
  localStorage.setItem("localemail", email);
  localStorage.setItem("localpassword", password);
  window.location.replace("https://accountdemo.netlify.app");
}

document.getElementById("registerButton").addEventListener("click", register);

The window.location.replace() method only works when I press the button alone. If I fill out the email & password fields and then press the button, it clears the forms, saves the data, and stays on the page it was currently on.

Why is this happening and how do I make it that it redirects when the input fields have been filled out?

HTML:

          <div class="inputbox">
            <ion-icon name="mail-outline"></ion-icon>
            <input type="email" id="emailData2" required>
            <label for="">Email</label>
          </div>
          <div class="inputbox">
            <ion-icon name="lock-closed-outline"></ion-icon>
            <input type="password" id="passwordData2" minlength="8" required>
            <label for="">Password</label>
          </div>
          <button id="registerButton">Sign Up</button>
          <div class="register">

Solution

  • Do you have a <form> outside the forms? Maybe it's due to the button triggered the form control. You can try

    function register(e) {
      e.preventDefault();
      e.stopPropagation();
      var email = document.getElementById("emailData2").value;
      var password = document.getElementById("passwordData2").value;
      localStorage.setItem("localemail", email);
      localStorage.setItem("localpassword", password);
      window.location.replace("https://accountdemo.netlify.app");
    }