I have an event listener attached to an HTML form element, but the listener is not getting triggered when I click on the button that submits the form or press "enter".
Here is the HTML:
<main class="main">
<div class="login-form">
<h2 class="heading-secondary ma-bt-lg">Log into your account</h2>
<form class="form" id="loginform">
<div class="form__group">
<label class="form__label" for="email">Email address</label>
<input class="form__input" id="email" type="email" placeholder="you@example.com" required="required"/>
</div>
<div class="form__group ma-bt-md">
<label class="form__label" for="password">Password</label>
<input class="form__input" id="password" type="password" placeholder="••••••••" required="required" minlength="8"/>
</div>
<div class="form__group">
<button class="btn btn--green" type="submit">Login</button>
</div>
</form>
</div>
</main>
Here is the event listener JS code:
const loginForm = document.getElementById('loginform');
if (loginForm) {
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
console.log('Hello from the login event listener');
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
login(email, password);
});
}
And here is the JS code for the function login(email, password)
, which is imported from another file:
export const login = async (email, password) => {
try {
const res = await axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/v1/users/login',
data: {
email,
password,
},
});
if (res.data.status === 'success') {
showAlert('success', 'Logged in successfully!');
window.setTimeout(() => {
location.assign('/home');
}, 1500);
}
} catch (err) {
showAlert('error', err.response.data.message);
}
};
Troubleshooting steps I've taken:
I figured out the problem. It was a dumb mistake on my part. In working to diagnose another problem, I'd added an event listener to the body element so that I could verify that click events were being generated (and see where they were being generated) when various DOM elements were clicked. BUT... I included an event.preventDefault() statement in that event listener, which shut down the default behavior on whatever was being clicked -- including the form element. Once I removed the event listener the form worked properly.
Thanks for your help everyone!