Skip to content

JavaScript FormData append | Method

  • by

JavaScript FormData append method is used to append a new value onto an existing key inside a FormData object or add the key if it does not already exist.

append(name, value)
append(name, value, filename)

JavaScript FormData append

Simple example code Append data to formData object.

<!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);

  formData.append('username', 'Chris');

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

</body>
</html>

Output:

JavaScript FormData append

The following line creates an empty FormData object:

var formData = new FormData(); // Currently empty

You can add key/value pairs to this using FormData.append:

formData.append('username', 'Chris');
formData.append('userpic', myFileInput.files[0], 'chris.jpg');

Do comment if you have any doubts or suggestions on this JS FormData 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