FormData Event Append Fields Before Submit

Hook the formdata event to append computed fields onto the entry list right before submission, without adding invisible inputs to the markup.

JavascriptForm Validation

Code

javascriptsnippet
21 lines
// The formdata event fires whenever the form's entry list is constructed -
// on submit and when FormData(form) is called - so computed fields can be
// appended there instead of adding invisible inputs to the markup.
if (typeof document === "undefined") {
  console.log("formdata event demo needs a browser DOM with #upload-meta");
} else {
  const form = document.querySelector("#upload-meta");

  form?.addEventListener("formdata", (event) => {
    event.formData.append("clientTimestamp", new Date().toISOString());
    if (!event.formData.has("priority")) {
      event.formData.append("priority", "normal");
    }
  });

  form?.addEventListener("submit", (event) => {
    event.preventDefault(); // demo page: inspect entries instead of navigating
    const keys = [...new FormData(form).entries()].map(([key]) => key);
    console.log("entry keys:", keys);
  });
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

formdata event demo needs a browser DOM with #upload-meta

The shape of the program

  • The environment needs no preparation beyond having the interpreter or compiler.
  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Applying it

Output lines are prefixed (entry keys:), so every step leaves a visible effect.

Statements that matter

form?.addEventListener("formdata", (event) => {
  event.formData.append("clientTimestamp", new Date().toISOString());
  if (!event.formData.has("priority")) {
    event.formData.append("priority", "normal");
  }
});
form?.addEventListener("submit", (event) => {
  event.preventDefault(); // demo page: inspect entries instead of navigating
  const keys = [...new FormData(form).entries()].map(([key]) => key);
  console.log("entry keys:", keys);
});

Interactive Tools for This Topic

FAQ

Does FormData Event Append Fields Before Submit run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.