I am having issues with a simple login page I am trying to make. It asks the user for a username and password and when login is pressed it should alert either success or fail, depending on whether the username and password are both admin. Currently when the login button is pressed the page just refreshes and the fields are cleared.
I would like to avoid having the javascript inline in the html file as I would rather have better separation.
function Verify() {
let loginForm = document.getElementById("loginForm")
var passref = "admin"
var userRef = "admin"
loginForm.addEventListener("submit", (e) => {
e.preventDefault();
var username = document.getElementById("uname").value;
var password = document.getElementById("pword").value;
if (username == userRef || password == passref) {
alert("Success")
}
else {
alert("Fail")
}
});
}
<form action="" id="loginForm">
<div class="container">
<label for="uname" id="uname"><b>Username</b></label>
<input type="text" placeholder="Enter username" id="uname" required>
<label for="pword"><b>Password</b></label>
<input type="password" placeholder="Enter password" id="pword" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me?
</label>
</div>
<div class="container" style="background-color: #f1f1f1;">
<button type="button" class="cancelBtn">Cancel</button>
<span class="forgot">Forgot <a href="#">password?</a></span>
</div>
</form>
I have tried multiple tests to see if the code is even being called, and it looks like the function isn’t being called. I have also tried an <input>
for for the login button and does not work.
2
Answers
If you remove your
label
s duplicate ID, unwrap theVerify
method (or call it but it seems you don’t want to add the listeners multiple times here anyway) and then make sure you fill in the required fields, it will start working as intended:We can always discuss if it is a good idea to validate a login form on the front-end. That aside, you can use the pattern attribute to validate the input elements. The form will only submit if the two input elements are valid. If you click the login button and the input elements are not valid a invalid event will be fired (or one for each invalid input element).
(I hope that you will give the user feedback, not using the alert box…)