Serialize Form
Converts HTML form elements into structured JavaScript objects or URL-encoded query strings.
serializeForm
Converts HTML form elements into structured JavaScript objects or URL-encoded query strings, handling both single and multiple input values.
Function Signature
function serializeForm<T extends boolean = false>(
form: HTMLFormElement,
toQueryString?: T
): SerializedForm<T>Parameters
| Parameter | Type | Description | Default |
|---|---|---|---|
form | HTMLFormElement | The form element to serialize. | — |
toQueryString | boolean (optional) | Return as a query string instead of an object. | false |
Returns
SerializedForm<T>:- A
Record<string, string | string[]>object (iftoQueryStringisfalse). - A
stringrepresenting a URL-encoded query string (iftoQueryStringistrue).
- A
Example Usage
import { serializeForm } from 'toolbox-x/dom';
// Assuming an HTML form with inputs: name="John", hobbies="reading", hobbies="coding"
const form = document.querySelector('form') as HTMLFormElement;
const data = serializeForm(form);
console.log(data);
// → { name: 'John', hobbies: ['reading', 'coding'] }Behavior Details
- Multiple Inputs: Multiple checkboxes with the same name or multi-select inputs automatically get serialized into arrays.
- File Inputs: File input values are serialized as their filename strings, not actual binary contents. For uploading files, use
createFormDatainstead.
Warning
Server-Side Rendering (SSR): This utility is a browser-only tool because it directly references and reads HTMLFormElement DOM nodes. It will throw errors in SSR contexts if executed server-side.
Types
SerializedForm
type SerializedForm<T extends boolean> = T extends false
? Record<string, string | string[]>
: string;Last updated: Mon, Jun 15, 2026 11:04:47AM (UTC)
