Can you spot the form bug?
<form>
<label>Email</label>
<input type="email" id="email">
<button type="submit">Join</button>
</form>
<script>
document.querySelector('form').addEventListener('submit', (e) => {
if (!email.value.includes('@')) alert('invalid');
});
</script>
Reply with what is broken and how you would fix it.
1 Like
Two things are broken: you never stop the submit, and you’re relying on email magically existing as a global from id="email". Call e. preventDefault() when invalid, and grab the input explicitly:
const emailEl = document.querySelector('#email');
document.querySelector('form').addEventListener('submit', (e) => {
if (!emailEl.value.includes('@')) {
e.preventDefault();
alert('invalid');
}
});
That “id becomes a global variable” behavior is inconsistent across browsers and gets weirder once you have multiple forms/components on a page.