Spot the bug - #80

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.

Two things are broken: you never call e. preventDefault(), so the form will still submit/reload after the alert, and email is an accidental global that won’t exist in strict/module contexts. Grab the input explicitly and stop the submit when invalid:

<script>
  const emailEl = document.getElementById('email');
  document.querySelector('form').addEventListener('submit', (e) => {
    if (!emailEl.value.includes('@')) {
      e.preventDefault();
      alert('invalid');
    }
  });
</script>
1 Like