Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onformdata — handling form data construction

The onformdata attribute defines a handler for the formdata event. It lets you inspect and modify form data after the entry list has been constructed, both during form submission and when new FormData(form) is called.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<form onformdata="event.formData.set('source', 'demo')">…</form>

onformdata is an event handler content attribute for formdata. Although available on HTML elements, its typical location is the form where this event originates. Its value is JavaScript code, not a Boolean value. The corresponding JavaScript property, form.onformdata, accepts a function; another option is form.addEventListener('formdata', handler).

The event fires after the form's entry list has been constructed, including during submission and through new FormData(form). The event object is a FormDataEvent, and event.formData exposes the collected data as FormData. The set(), append(), and delete() methods can modify that data. During submission, these changes affect the submitted data set, but do not change the values of the form controls.

Do not confuse formdata with submit: calling new FormData(form) does not itself submit the form. The formdata event bubbles but is not cancelable; preventDefault() will not stop submission. Handle submit to cancel submission instead.

The example constructs data without submitting the form. The onformdata code adds the source entry before the constructor returns its result. A Content Security Policy can block attribute-based handlers; in that environment, use addEventListener() in an allowed script.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onformdata demo</title>
<form id="demo" onformdata="event.formData.set('source', 'demo')">
  <input type="hidden" name="topic" value="html">
</form>
<pre id="result"></pre>
<script>
  const form = document.getElementById('demo');
  const data = new FormData(form);
  document.getElementById('result').textContent =
    JSON.stringify(Array.from(data.entries()));
</script>
</html>

Result

[["topic","html"],["source","demo"]]

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources