Home > Software engineering >  Using submit type but IF statement does not work
Using submit type but IF statement does not work

Time:06-20

I am trying to make a very simple login page for a website I created and I am having issues with the submit button. I got the submit button to work fine if I use a "button" type in HTML however the Enter key does not work then. I discovered if I use a "submit" type, the Enter button and the mouse click will work however... the button now goes over my IF statement, straight to my Else statement. Any help would be appreciated.

HTML form:

      <form>
        <label for="pswd">ENTER PASSWORD</label>
        <br>
        <input  type="password" id="pswd">
        <br>
        <input  type="submit" value="SUBMIT" onclick="checkPswd();" />
      </form>

JS code:

function checkPswd() {
var confirmPassword = "08012020";
var password = document.getElementById("pswd").value;
if (password == confirmPassword) {
  window.location = "index.html";
}
else{
    alert("Password is incorrect, Please try again.")
}

}

Again, Thank you in advance...

CodePudding user response:

I have a JSFiddle with a working example of what you are hoping to accomplish here. The key is returning false after calling your function, so the page redirect is not triggered by the input submission:

function checkPswd() {
  let confirmPassword = "08012020";
  let password = document.getElementById("pswd").value;
  
  if (password === confirmPassword) {
    alert("CORRECT!");
  } else{
    alert("Password is incorrect, Please try again.")
  }
}
<form>
  <label for="pswd">ENTER PASSWORD</label>
  <br>
  <input  type="password" id="pswd">
  <br>
  <input  type="submit" value="SUBMIT" onclick="checkPswd(); return false;" />
</form>

I would like to add that performing client-side password checking is very insecure since the source code can easily be inspected, so if you are hoping to use this in a real website I would suggest you consider a different approach!

  • Related