Ad

Using Form Instead Of Div

I have login page. In which I am using form. It never worked. Later I tried div and it works fine. Can anyone tell me why it does not work with form.

Edit: I'm trying to login with firebase. While using form it gives an error.But while using div it logs me in.

<div class="login-clean" id="login_div">
  <form method="post">
    <h2 class="sr-only">Login Form</h2>
    <div class="illustration"><i class="icon ion-ios-navigate"></i></div>
    <div class="form-group"><input class="form-control" type="email" name="email" id="email_field" placeholder="Email"></div>
    <div class="form-group"><input class="form-control" type="password" name="password" id="password_field" placeholder="Password"></div>
    <div class="form-group"><button class="btn btn-primary btn-block" onclick="login()" type="submit">Log In</button></div><a target="_blank" rel="nofollow noreferrer" href="#" class="forgot">Forgot your email or password?</a>
  </form>
</div>

function login(){
  var userEmail = document.getElementById("email_field").value;
  var userPass = document.getElementById("password_field").value;

  firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;

    window.alert("Error : " + errorMessage);

    // ...
  });
}
Ad

Answer

A submit button within a form is going to submit the form. So, after the onclick handler is triggered i.e. login is called. the page is refreshed with the form values submitted.

To prevent the button from submitting the form after logging in, change it to:

<input class="btn btn-primary btn-block" onclick="login()" type="button">
Ad
source: stackoverflow.com
Ad