skip to Main Content
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">

2

Answers


  1. I haven’t tried this with your markup but this would attach the event listener to the document itself rather then the button that I suspect is being updated loosing the attached event

    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.addEventListener("click", function(e){
      const targetId = e.target.id
        
      if(targetId == 'registerButton'){
        register();
      }
    });
    
    Login or Signup to reply.
  2. 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");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search