I have created a Login-form, basically like so:
<form class="form" id="login" th:action="@{/login}" method="post">
<input type="text" class="form__input" id="username" name="username" autofocus placeholder="Username or eMail" />
<input type="password" class="form__input" id="password" name="password" placeholder="Password" />
<button class="form__button" type="submit">Login</button>
</form>
I have attached a js file to this html page, in which I add the following listeners:
const form = document.querySelector("#login");
const submitButton = document.querySelector("button");
const usernameInputField = document.querySelector("#username");
const passwordInputField = document.querySelector("#password");
form.addEventListener("submit", e => {
checkInputValidity("user");
checkInputValidity("password");
if (!isInputValid()) {
e.preventDefault();
}
});
passwordInputField.addEventListener("keyup", e => {
if (e.keyCode === 13) {
submitButton.focus();
form.submit();
}
})
I think important is the checkInputValidity() method:
function checkInputValidity(type) {
switch (type) {
case "user":
isEmpty(usernameInputField.value) ?
isUsernameValid = false :
isUsernameValid = true;
break;
case "password":
isEmpty(passwordInputField.value) ?
isPasswordValid = false :
isPasswordValid = true;
break;
}
}
isInputValid() simply checks if either of the input fields is empty and then returns false, else returns true:
function isInputValid() {
return !!(isUsernameValid && isPasswordValid);
}
Here is the problem:
After I have entered the correct login data, when clicking on the Login-button, I have successfully logged in. However, when entering the correct login data and hitting the 'Enter' button, I am just redirected to my Login-page. This seems to be related to the checkInputValidity() method as removing this method from my form-submit-listener reverts the issue: Now, when clicking on the Login-button, nothing happens. But when hitting the 'Enter' button, I am successfully logged in.
This whole behavior is very strange to me. Can somebody help me out?