How do you serialize HTML form fields into a JavaScript object using jQuery? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you serialize HTML form fields into a JavaScript object using jQuery?

message-square
0

To serialize HTML form fields into a JavaScript object using jQuery, validate that the target is a non-empty jQuery collection ($form instanceof $ and $form.length > 0) or HTMLFormElement, extract serialized name/value pairs with $form.serializeArray() (rather than $form.serialize(), which produces a URL-encoded query string), normalize values into a Map first to avoid Object.prototype collisions, and convert or read keys safely inside a try / catch block while accounting for multi-value fields (checkboxes / <select multiple>), unchecked checkboxes/radios, disabled inputs, and file inputs (<input type="file">).


1. Converting $form.serializeArray() into a Object / Map Safely

jQuery’s .serializeArray() returns an array of { name, value } objects for successful form controls. Validate inputs, store entries in a Map, and build a clean plain object inside try / catch:

// Serialize jQuery form fields into a plain object using serializeArray() and Map
function serializeFormToObject(formTarget, {
  jqueryRef = (typeof $ !== "undefined" ? $ : null),
  includeEmpty = true
} = {}) {
  if (typeof jqueryRef !== "function") {
    throw new TypeError("Expected jqueryRef to be a valid jQuery ($) function.");
  }
  if (typeof includeEmpty !== "boolean") {
    throw new TypeError("Expected includeEmpty to be a boolean.");
  }

  const $form = formTarget instanceof jqueryRef
    ? formTarget
    : (formTarget instanceof HTMLFormElement ? jqueryRef(formTarget) : null);

  if (!$form || !($form instanceof jqueryRef) || $form.length === 0) {
    throw new TypeError("Expected formTarget to be a non-empty jQuery collection or HTMLFormElement.");
  }
  if (!($form.get(0) instanceof HTMLFormElement)) {
    throw new TypeError("Expected first matched element to be an HTMLFormElement.");
  }
  if (typeof $form.serializeArray !== "function") {
    throw new Error("Expected jQuery collection to support serializeArray().");
  }

  try {
    const serializedEntries = $form.serializeArray();
    const fieldsMap = new Map();

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

      const fieldName = item.name;
      const fieldValue = typeof item.value === "string" ? item.value : String(item.value ?? "");

      if (!includeEmpty && fieldValue.length === 0) {
        continue;
      }

      if (fieldsMap.has(fieldName)) {
        const existing = fieldsMap.get(fieldName);
        if (Array.isArray(existing)) {
          existing.push(fieldValue);
        } else {
          fieldsMap.set(fieldName, [existing, fieldValue]);
        }
      } else {
        fieldsMap.set(fieldName, fieldValue);
      }
    }

    const resultObject = {};
    for (const [key, val] of fieldsMap.entries()) {
      Object.defineProperty(resultObject, key, {
        value: val,
        enumerable: true,
        configurable: true,
        writable: true
      });
    }

    return resultObject;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed serializing jQuery form into object: ${message}`);
  }
}

// Example usage:
// try {
//   const formDataObj = serializeFormToObject($("#profile-form"));
//   console.log("Serialized form:", formDataObj);
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Use .serializeArray() instead of .serialize(): .serialize() returns a query string ("name=Ali&role=admin"), whereas .serializeArray() exposes structured { name, value } items.
  • Aggregate repeated names into arrays: Multiple checked boxes or <select multiple> options with the same name are preserved instead of overwriting earlier values.

2. Handling Repeated Keys, Types, and Normalizations with a Map

When a form contains repeated keys (such as tags or permissions[]), numeric/boolean strings, or dangerous field names (__proto__, constructor, toString), keep working state in a Map before converting or returning structured values:

// Collect serialized form fields into a normalized Map with optional type coercion
function serializeFormToMap(formElementOrSelector, {
  jqueryRef = (typeof $ !== "undefined" ? $ : null),
  coercePrimitives = false
} = {}) {
  if (typeof jqueryRef !== "function") {
    throw new TypeError("Expected jqueryRef to be a valid jQuery ($) function.");
  }
  if (typeof coercePrimitives !== "boolean") {
    throw new TypeError("Expected coercePrimitives to be a boolean.");
  }

  const $form = formElementOrSelector instanceof jqueryRef
    ? formElementOrSelector
    : jqueryRef(formElementOrSelector);

  if (!($form instanceof jqueryRef) || $form.length === 0) {
    throw new Error("Form selector or element did not match any DOM node.");
  }
  if (!($form.get(0) instanceof HTMLFormElement)) {
    throw new TypeError("Matched element must be an HTMLFormElement.");
  }

  try {
    const entries = $form.serializeArray();
    const normalizedMap = new Map();

    const normalizeValue = (rawVal) => {
      if (!coercePrimitives) {
        return rawVal;
      }
      if (rawVal === "true") {
        return true;
      }
      if (rawVal === "false") {
        return false;
      }
      if (rawVal.trim() !== "" && !Number.isNaN(Number(rawVal))) {
        return Number(rawVal);
      }
      return rawVal;
    };

    for (const entry of entries) {
      if (!entry || typeof entry.name !== "string" || entry.name.length === 0) {
        continue;
      }

      const normalizedVal = normalizeValue(String(entry.value ?? ""));
      if (normalizedMap.has(entry.name)) {
        const current = normalizedMap.get(entry.name);
        if (Array.isArray(current)) {
          current.push(normalizedVal);
        } else {
          normalizedMap.set(entry.name, [current, normalizedVal]);
        }
      } else {
        normalizedMap.set(entry.name, normalizedVal);
      }
    }

    return normalizedMap;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed serializing jQuery form into Map: ${message}`);
  }
}

// Example usage:
// try {
//   const dataMap = serializeFormToMap("#order-form", { coercePrimitives: true });
//   console.log("Quantity:", dataMap.get("quantity"));
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Use Map for arbitrary user-controlled field names: Avoids Object.prototype collisions on keys like constructor or hasOwnProperty.
  • Keep coercePrimitives: false when exact string formatting matters: Leading zeros (such as PINs or postal codes) are stripped if numeric coercion runs blindly.

3. Successful Form Controls, File Inputs, and Caveats

Keep these jQuery serialization rules in mind so form payloads match expectations:

  • Controls without a name attribute are ignored by .serializeArray(): Every input, select, or textarea you want serialized must have a non-empty name.
  • Unchecked checkboxes/radios and disabled controls are omitted: .serializeArray() only includes “successful controls” per HTML form rules.
  • <input type="file"> is not serialized into text values by .serializeArray(): Use new FormData(formElement) when uploading files via fetch or $.ajax (processData: false, contentType: false).