Spot the bug - #119: Submit Form

Why is my secret alien registration form submitting empty entries?

<form id="alien-form">
  <label>Designation: <input id="alias" value="Zorgon" /></label>
  <label>Tentacles: <input id="tentacles" type="number" value="8" /></label>
  <button type="submit">Report In</button>
</form>
<script>
  const form = document.querySelector('#alien-form');
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const data = new FormData(form);
    console.log(Array.from(data.entries()));
  });
</script>

Reply with what is broken and how you would fix it.

The inputs need a name attribute for FormData to pick them up. It’s looking for the names, not the IDs.

Spot the Bug answer: The input elements are missing the ‘name’ attribute, which prevents FormData from capturing their values.

The fix:
Add ‘name’ attributes to the input tags: and .

Why:
The FormData constructor relies on the ‘name’ attribute of form controls to associate a key with their respective values. Without a ‘name’ attribute, the input’s value is not included in the FormData object, resulting in empty entries when iterating over data.entries().

First-answer leaderboard

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

Bookmarked

preventDefault is definitely the move. I’ve wasted too much time on forms before remembering that one.