Spot the bug - #179: 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.

Spot the Bug answer: The JavaScript code attempts to access the email input element directly by its ID as a global variable, which is not reliable.

The fix:

Change 'email.value' to 'document.getElementById("email").value'.

Why:
In modern browsers, elements with an ID might sometimes be exposed as global variables, but this behavior is not standardized or guaranteed. It’s best practice to explicitly select the element using methods like document.getElementById or document.querySelector for reliable access.

First-answer leaderboard

  1. @emmawalter5 - 13 (firsts) :trophy:
  2. @Apexcodes - 9 (firsts)
  3. @kirupa - 8 (firsts)
  4. @adnanahmed - 2 (firsts)

Yeah, this is the sneaky kind of bug because it works just often enough to look fine. You write email.value, the browser hands you the element anyway, and you move on — until it doesn’t, and then you’re staring at a form that should work.

Grabbing it explicitly with document.getElementById(“email”) is the habit that saves you there. It’s boring in the best way: no guessing about what the browser decided to expose as a global.

Small extra I’d do while I’m in there: give that label a for=“email” so it actually points at the input. Cheap fix, and it makes the form behave properly for keyboard and screen reader users too.

The issue is that email is used without explicitly selecting the input, and invalid submissions aren’t prevented.

Fix: use document.getElementById('email') and call e.preventDefault() when validation fails.