Home > OS >  Log in form not redirecting to new page / registering log in
Log in form not redirecting to new page / registering log in

Time:03-06

Have tried different methods of validating username and password, and sending to the new page but page just reloads after clicking button. Had thought preventDefault() would stop this. If anyone notices the problem, please let me know, thanks.

const loginForm = document.querySelector('login-form')
const loginButton = document.querySelector('login-form-submit')
loginButton.addEventListener("click", (e) => {
  e.preventDefault();
  const username = loginForm.username.value;
  const password = loginForm.password.value;
  if (username === 'admin' && password === 'admin1') {
    alert("You have logged in!");
    window.open('Data.html');
  } else {
    alert("Incorrect Password");
  }
})
<div >
  <form id="login-form">
    Sign in to access your account
    <br>
    <br>
    <label for="name">Account Name:</label>
    <input type="text" id="username-field" name="username"  placeholder="Username"><br><br>
    <label for="password">Account Password:</label>
    <input type="password" id="password-field" name="password"  placeholder="Password"><br><br>
    <input type="submit" value="Log In" id="login-form-submit">
  </form>
</div>

CodePudding user response:

The easiest way to do is to use input type="button", just change from submit to button

<input type="button" value="Log In" id="login-form-submit" />

Also, you have an error in your document.querySelector. To get element by id, you need to use # like

document.querySelector('#login-form-submit')

CodePudding user response:

loginForm.addEventListener('submit', function(e){
    e.preventDefault();
    const username = e.currentTarget.querySelector('[name="username"]').value;
    const password = e.currentTarget.querySelector('[name="password"]').value;
})
  • Related