formToObject

Documentation of formToObject

This page gives the full data about formToObject(), version 4. For the installation and a short example, refer to the README. For the changes from version 3, refer to the changelog.

Contents:

Function

formToObject(form, options);

formToObject() reads the fields of one HTML form and returns one JavaScript object.

Parameter Description
form A CSS selector (a string) or the <form> element.
options An object that contains options. This parameter is not necessary. Refer to Options.

The function returns one of these values:

A string is always a CSS selector. Thus '#myForm' finds the element that has the ID myForm, but 'myForm' does not find it.

// The ID of the form
formToObject('#myForm');

// A class of the form
formToObject('.registration-form');

// An attribute of the form
formToObject('form[data-type="checkout"]');

// The element
formToObject(document.querySelector('form'));

Example

<form id="settingsForm">
  <input name="settings[player][name]" value="serbanghita">
  <select name="settings[player][race]">
    <option value="human">human</option>
    <option value="orc" selected>orc</option>
  </select>
  <textarea name="settings[player][description]">This is a description.</textarea>

  <input type="radio" name="settings[input]" value="mouse">
  <input type="radio" name="settings[input]" value="keyboard" checked>
  <input type="radio" name="settings[input]" value="touch">

  <select name="settings[video][resolution]">
    <option value="1280 x 720">1280 x 720</option>
    <option value="1920 x 1080" selected>1920 x 1080</option>
  </select>
  <input type="checkbox" name="settings[video][vertical_sync]" checked>
</form>

formToObject('#settingsForm') returns this object:

{
  "settings": {
    "player": {
      "name": "serbanghita",
      "race": "orc",
      "description": "This is a description."
    },
    "input": "keyboard",
    "video": {
      "resolution": "1920 x 1080",
      "vertical_sync": "on"
    }
  }
}

Field names

The name of a field gives the position of its value in the result. A name can contain brackets (PHP syntax), dots (Spring MVC syntax), or brackets and dots together.

Syntax Field names Result
No brackets or dots email {email: "a@b.c"}
Same name tag, tag {tag: ["a", "b"]}
Bracket keys user[address][zip] {user: {address: {zip: "10001"}}}
Empty brackets tags[], tags[] {tags: ["a", "b"]}
Key, then empty brackets d[x][], d[x][] {d: {x: ["1", "2"]}}
Numeric index items[0][name], items[1][name] {items: [{name: "a"}, {name: "b"}]}
Array of objects items[][name], items[][qty], items[][name], items[][qty] {items: [{name: "a", qty: "1"}, {name: "b", qty: "2"}]}
Dots customer.address.zip {customer: {address: {zip: "10001"}}}
Index, then a dot items[0].name, items[1].name {items: [{name: "a"}, {name: "b"}]}
Key in quotation marks attrs['color'] {attrs: {color: "red"}}

These rules apply:

Fields with the same name

Fields that have the same name are a group, and a group gives an array.

Form Result
2 text inputs with the name tag {tag: ["a", "b"]}
The same inputs, but only the first has a value {tag: ["a"]}
The same inputs, but the 2 inputs are empty {}
The same inputs with repeatedNames: 'last' {tag: "b"}

These rules apply:

Checkboxes and radio buttons

A browser sends no data for a checkbox that is not checked. formToObject() gives a value for such a checkbox. Thus the result also shows that the user removed a selection.

Form Result
One checkbox with the name agree and value="yes", checked {agree: "yes"}
The same checkbox without a value attribute {agree: "on"}
The same checkbox, not checked {agree: false}
3 checkboxes with the name devices, 2 checked {devices: ["mouse", "keyboard"]}
The same group, one checked {devices: ["mouse"]}
The same group, none checked {devices: []}
Radio buttons with the name plan, one selected {plan: "pro"}
Radio buttons with the name plan, none selected {plan: false}

These rules apply:

Some forms have a hidden input and a checkbox with the same name. The hidden input gives a value when the checkbox is not checked. These 2 fields are a group. When the checkbox is checked, the result is {agree: ["0", "1"]}. With repeatedNames: 'last', the result is {agree: "1"}.

Fields that the result does not include

The function ignores these fields:

The function gets the fields from the list of controls of the form. Thus the result includes a field that is not in the <form> element but has a form attribute with the ID of the form.

Options

Option Type Default Description
includeEmptyValuedElements boolean false The result includes the fields that have an empty value. Their value is "".
includeSubmitButton boolean false The result includes <button> and <input type="submit"> fields.
includeDisabledFields boolean false The result includes disabled fields, fields in a <fieldset disabled>, and disabled <option> elements.
repeatedNames 'array' or 'last' 'array' The value that a group of fields with the same name gives: an array of all the values, or the last value.
dotNotation boolean true A dot in a field name is between 2 keys. When the option is false, a dot is a part of the key.

The function ignores the keys that are not in this table.

formToObject('#myForm', { includeEmptyValuedElements: true, repeatedNames: 'last' });

TypeScript

The package includes the TypeScript types. You can give the type of the result as a generic type parameter.

import formToObject from 'form_to_object';

interface UserSettingsForm {
  name: string;
  email: string;
  // A checkbox that has its own name gives its value or false.
  newsletter: string | false;
  settings: {
    theme: 'light' | 'dark';
  };
}

const data = formToObject<UserSettingsForm>('#settingsForm');

if (data) {
  console.log(data.name);           // string
  console.log(data.settings.theme); // 'light' | 'dark'
}

The type of the options is IFormToObjectOptions. An option that is not in the Options table causes a type error.

Script and browsers

The script is a UMD bundle of approximately 9 kB (3.5 kB with gzip). It adds the global function formToObject.

<!-- From the npm package -->
<script src="node_modules/form_to_object/build/bundle/formToObject.min.js"></script>

<!-- From jsDelivr (CDN) -->
<script src="https://cdn.jsdelivr.net/npm/form_to_object@4.0.0/build/bundle/formToObject.min.js"></script>

The library operates in these browsers: Chrome, Edge, Firefox and Safari. The library does not operate in Internet Explorer, because the bundle is ES2015 code. The tests of the library use Chromium.