Skip to content

JavaScript FormData | API

  • by

JavaScript FormData interface allows you to construct a set of key/value pairs representing form fields and their values. If HTML form element is provided, it automatically captures its fields.

let formData = new FormData([form]);

The FormData is those network methods, such as fetch, can accept a FormData object as a body. It’s encoded and sent out with Content-Type: multipart/form-data.

JavaScript FormData

A simple example code has two input fields for name and age respectively and onSubmit function of this form.

<!DOCTYPE html>
<html>
<head>
  <style type="text/css">
    input {
      margin: 5px;
      padding: 4px;
    }
  </style>
</head>

<body>

 <form id="testForm">
  <input type="text" name="name" placeholder="Name"><br>
  <input type="text" name="age" placeholder="Age"><br>
  <input type="submit" value="Submit">
</form>

<script>
 testForm.onsubmit = (e) => {
  e.preventDefault();
  const formData = new FormData(testForm);

  console.log("Form Data");
  for (let obj of formData) {
    console.log(obj);
  }
};
</script>

</body>
</html>

Output:

JavaScript FormData

FormData Methods

We can modify fields in FormData with methods:

  • formData.append(name, value) – add a form field with the given name and value,
  • formData.append(name, blob, fileName) – add a field as if it were <input type="file">, the third argument fileName sets file name (not form field name), as if it were a name of the file in the user’s filesystem,
  • formData.delete(name) – remove the field with the given name,
  • formData.get(name) – get the value of the field with the given name,
  • formData.has(name) – if there exists a field with the given name, returns true, otherwise false

Do comment if you have any doubts or suggestions on this Js interface topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading