Categories
JavaScript Answers

How to fix FormData entries not showing in console with JavaScript?

Spread the love

If FormData entries are not showing in the console, it’s likely because you’re trying to log the FormData object directly.

The FormData object is not a simple JavaScript object, so logging it directly won’t display its contents in the console.

Instead, you need to iterate over its entries and log each entry individually.

For instance we write:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Logging FormData Entries</title>
</head>
<body>

  <form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <br>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
    <br>
    <input type="submit" value="Submit">
  </form>

  <script>
    document.getElementById("myForm").addEventListener("submit", function(event) {
      event.preventDefault(); // Prevent form submission

      var formData = new FormData(this);

      // Log FormData entries
      for (var pair of formData.entries()) {
        console.log(pair[0] + ": " + pair[1]);
      }
    });
  </script>

</body>
</html>

In this example, when the form is submitted, a new FormData object is created from the form.

Then, a for…of loop is used to iterate over the entries of the FormData object.

Each entry is an array [key, value], where pair[0] represents the key (name of the form field) and pair[1] represents the value (value of the form field).

These key-value pairs are logged to the console individually.

This way, you can see the contents of the FormData object in the console.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *