Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT FORMS / CHAPTER 05 / Learn / LESSON 04
Theory. new FormData(form) collects every field of the form that has a name. You do not search for each field one by one: data.get("name") returns a value (string) or null.
Key rule: an unchecked checkbox is NOT in FormData at all — the key is missing. So data.get("paid") is null, not "false". A submit button without a name is not included either.
Small examples:
const data = new FormData(form); const name = data.get("name"); const rows = []; for (const [key, value] of data.entries()) rows.push(key + "=" + value); const text = rows.join(";");
The order follows the field order in the DOM. Fields without a name (id only) are invisible to FormData.
Common mistake: looking for id instead of name; expecting false for an unchecked checkbox; reading FormData outside a submit/click listener.
<form id="f"><input id="name" name="name" type="text"><input id="amount" name="amount" type="text"><label><input id="paid" name="paid" type="checkbox" value="yes"> Paid</label><button type="submit">Save</button></form><p id="out"></p>FormData collects fields with a name; an unchecked checkbox is missing entirely.
Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›