Spot the bug - #146: 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 using a global variable ‘email’ which is not reliably defined.

The fix:

Change 'email.value' to 'document.getElementById("email").value' or 'e.target.elements.email.value'.

Why:
In modern browsers, IDs of elements are sometimes exposed as global variables, but this is not standard or reliable behavior. The correct way to access an element by its ID in JavaScript is to use ‘document.getElementById()’. Relying on global ID access can lead to errors, especially if there are other variables named ‘email’ or in different execution contexts.

First-answer leaderboard

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

This is a good reminder about relying on global variables. I’ve seen weird bugs from this kind of thing.