Get form fields as a JSON Object in JavaScript

We will see in this post how to access the values of the elements of a form using JavaScript. The getFormData method will allow us to retrieve from a provided form all the fields filled in as an object, in our case input, textarea and select.

We can also allow more elements and at the same time exclude some inputs such as button, reset, submit that may not be essential for our case. This method can be useful for sending data from a form as an object, on click.

Note that this code is made in the simplest possible way. We could of course split some parts and make functions for all the conditions where we check the type of the element, if it has multiple values…

const getFormData = form => {
  if (!form || form.tagName !== "FORM") return;

  const { elements } = form;
  // object of the data we are going to retrieve
  const data = {};
  // the HTML tags we want to retrieve
  const allowedTags = ["INPUT", "TEXTAREA", "SELECT"];
  // the types of inputs that we dont consider
  const excludedInputTypes = ["button", "reset", "submit"];

  // [].slice.call() will convert elements of type HTMLFormControlsCollection to an array
  [].slice
    .call(elements)
    .filter(
      node =>
        // we return the tag only if it is contained in `allowedTags`
        // and if its name has a value
        allowedTags.indexOf(node.tagName) !== -1 && node.name
    )
    .forEach(node => {
      // in the case of an input
      if (
        node.tagName === "INPUT" &&
        excludedInputTypes.indexOf(node.type) === -1
      ) {
        if (
          (node.type !== "radio" && node.type !== "checkbox") ||
          (node.type === "radio" && node.checked)
        ) {
          data[node.name] = node.value;
        }
        if (node.type === "checkbox") {
          data[node.name] = node.checked;
        }
      }

      // in the case of a textarea
      if (node.tagName === "TEXTAREA") {
        data[node.name] = node.value;
      }

      // in the case of a select with options
      if (node.tagName === "SELECT") {
        const hasOption =
          node.options.length && node.options[node.selectedIndex];
        data[node.name] = hasOption
          ? node.options[node.selectedIndex].value
          : "";
      }
    });
  return data;
};

// let's assume we have a form with the id `#my-form` 
// and all its fields have a `name` attribute
const myForm = document.getElementById("my-form");
console.log(getFormData(myForm));

Before you leave…
Thanks for reading! 😊