Spot the bug - #69

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 here: you never stop the submit, and email is a sketchy global. Right now it’ll alert “invalid” and still submit/reload because you don’t call e. preventDefault(). And email. value only “works” in some browsers because elements with an id sometimes get exposed as globals; in strict/module code it’ll just be a ReferenceError.

const emailInput = document.querySelector('#email');
document.querySelector('form').addEventListener('submit', (e) => {
  if (!emailInput.value.includes('@')) {
    e.preventDefault();
    alert('invalid');
  }
});