Spot the bug - #105: Email Signup Form

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.

The email variable is used but not declared.

Guess is in, noted. Answer drops later today, staying quiet until then.

Spot the Bug answer: The submit handler never calls e.preventDefault(), so even when the email is invalid the form still submits and the page reloads/navigates before or despite the alert.

The fix:

if (!email.value.includes('@')) { e.preventDefault(); alert('invalid'); }

Why:
Adding a listener does not stop the default form submission automatically; you must explicitly call preventDefault() to block navigation when validation fails. As written, the alert shows but the browser proceeds to submit the form anyway.


Nobody got this one. It was a sneaky one.

Close but not quite:

@kirupa - email is actually accessible globally because browsers auto-expose elements with an id as global variables, so that’s not the bug; they missed the missing preventDefault() causing the form to submit anyway.

First-answer leaderboard

  1. @emmawalter5 - 1 (first) :trophy:
  2. @kirupa - 1 (first) :trophy:
1 Like