How do you collect and serialize HTML form data using JavaScript FormData or jQuery? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you collect and serialize HTML form data using JavaScript FormData or jQuery?

message-square
0

To collect and serialize HTML form data in vanilla JavaScript, pass an HTMLFormElement to new FormData(form) and convert entries into a plain object (via Object.fromEntries(formData.entries()) or a multi-value helper for checkboxes/select-multiple), a query string (via new URLSearchParams(formData).toString()), or a JSON string (via JSON.stringify(...)); in jQuery, use $form.serialize() for a URL-encoded query string (a=1&b=2), $form.serializeArray() for an array of { name, value } objects, or new FormData($form[0]) when including File uploads (<input type="file">). Note that FormData and .serialize() only include named (name="..."), enabled (not disabled) form controls, and standard serialization formats turn all values into strings.


1. Collecting and Serializing Form Data in Vanilla JS with FormData

Instantiate new FormData(formElement) without mutating the form, then transform the entries into a plain object, URL query string, or JSON payload:

// Convert a FormData instance into a plain object, preserving multiple values as arrays
function formDataToObject(formData) {
  if (!(formData instanceof FormData)) {
    throw new TypeError("Expected an instance of FormData.");
  }

  const result = {};

  for (const [key, value] of formData.entries()) {
    if (Object.prototype.hasOwnProperty.call(result, key)) {
      result[key] = Array.isArray(result[key])
        ? [...result[key], value]
        : [result[key], value];
    } else {
      result[key] = value;
    }
  }

  return result;
}

// Serialize a form element to an object, URL-encoded query string, and JSON string
function serializeForm(formElement) {
  if (!(formElement instanceof HTMLFormElement)) {
    throw new TypeError("Expected an HTMLFormElement instance.");
  }

  const data = new FormData(formElement);
  const record = formDataToObject(data);

  // Build URLSearchParams from string values (excluding raw File objects)
  const params = new URLSearchParams();
  for (const [key, value] of data.entries()) {
    if (!(value instanceof File)) {
      params.append(key, String(value));
    }
  }

  return {
    formData: data,
    object: record,
    queryString: params.toString(),
    json: JSON.stringify(record)
  };
}

// Example usage (in a browser):
// const form = document.querySelector("#profile-form");
// if (form) {
//   const serialized = serializeForm(form);
//   console.log(serialized.object, serialized.queryString, serialized.json);
// }
  • Multiple values for the same name: Object.fromEntries(formData.entries()) overwrites earlier values when multiple checkboxes or <select multiple> options share a name; formDataToObject() preserves repeated keys as an array.
  • Sending multipart/form-data: Pass new FormData(formElement) directly as the body of fetch() when uploading files—do not manually set Content-Type so the browser can attach the proper multipart boundary.

2. Collecting and Serializing Form Data with jQuery

In jQuery, .serialize() produces a URL-encoded query string ready for application/x-www-form-urlencoded requests, .serializeArray() returns { name, value } pairs, and $form[0] gives you the underlying DOM element for new FormData($form[0]):

// Non-mutating helper to serialize a jQuery form selection into useful formats
function serializeJqueryForm($form) {
  if (!($form && $form.length > 0 && $form[0] instanceof HTMLFormElement)) {
    throw new TypeError("Expected a jQuery collection wrapping an HTMLFormElement.");
  }

  const queryString = $form.serialize();
  const entriesArray = $form.serializeArray();
  const mapObject = {};

  for (const item of entriesArray) {
    if (!item || typeof item.name !== "string") {
      continue;
    }

    // Normalize \r\n line endings per HTML form serialization conventions
    const normalizedValue = String(item.value ?? "").replace(/\r?\n/g, "\r\n");

    if (Object.prototype.hasOwnProperty.call(mapObject, item.name)) {
      mapObject[item.name] = Array.isArray(mapObject[item.name])
        ? [...mapObject[item.name], normalizedValue]
        : [mapObject[item.name], normalizedValue];
    } else {
      mapObject[item.name] = normalizedValue;
    }
  }

  return {
    queryString,
    entriesArray,
    object: mapObject,
    json: JSON.stringify(mapObject),
    formData: new FormData($form[0])
  };
}

// Example usage (in a browser with jQuery):
// const serializedJq = serializeJqueryForm($("#checkout-form"));
// console.log(serializedJq.queryString, serializedJq.json);
  • .serialize() skips unchecked boxes and file contents: Unchecked checkboxes/radios and disabled inputs are omitted; <input type="file"> only exposes file names in .serializeArray(), whereas new FormData($form[0]) captures the File objects.
  • Keep form inputs untouched: Reading FormData or calling .serialize() does not mutate the form’s values or DOM structure.

3. Common Edge Cases: Missing name, Disabled Fields, and Types

Always verify that inputs have name attributes and convert numeric or boolean fields intentionally if your backend or state expects typed values rather than strings:

// Non-mutating helper to coerce selected string fields into numbers or booleans
function coerceFormFields(rawObject, schema = {}) {
  if (!rawObject || typeof rawObject !== "object" || Array.isArray(rawObject)) {
    throw new TypeError("Expected rawObject to be a plain object.");
  }

  const next = { ...rawObject };

  for (const [key, expectedType] of Object.entries(schema)) {
    if (!Object.prototype.hasOwnProperty.call(next, key)) {
      continue;
    }

    const val = next[key];
    if (expectedType === "number") {
      const parsed = Number(val);
      next[key] = Number.isNaN(parsed) ? null : parsed;
    } else if (expectedType === "boolean") {
      next[key] = val === true || val === "true" || val === "on" || val === "1";
    }
  }

  return next;
}

// Example usage:
console.log(coerceFormFields({ age: "28", subscribe: "on", note: "hi" }, {
  age: "number",
  subscribe: "boolean"
})); // { age: 28, subscribe: true, note: "hi" }
  • Unnamed controls are ignored: An <input id="email"> without name="email" will not appear in FormData, .serialize(), or .serializeArray().
  • Stringified values by default: Form serialization produces strings ("42", "true"), so coerce types explicitly when building JSON APIs.

TL;DR: Use new FormData(form) in vanilla JS (with formData.entries(), URLSearchParams, or JSON.stringify(...)) for full control including files, or $form.serialize() / $form.serializeArray() (and new FormData($form[0]) for files) in jQuery.