serbanghita/form-to-object.js

Plain JavaScript method to convert a HTML form (fields and values) to JavaScript (multidimensional) object.

Installs: 26

Dependents: 0

Suggesters: 0

Security: 0

Stars: 89

Watchers: 12

Forks: 25

Language:TypeScript

v3.0.0-rc.0 2023-12-19 21:02 UTC

This package is auto-updated.

Last update: 2024-10-29 08:16:55 UTC


README

Convert HTML forms with all their fields and values to multidimensional JavaScript objects

Workflow status Codecov branch npm version npm downloads

Install

As a npm package:

npm install form_to_object
import formToObject from 'form_to_object';
// or
const formToObject = require('form_to_object');

As a JS script:

<!-- Include minified script (~6kb) -->
<script src="build/formToObject.js"></script>

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

Example

  • Using the DOM node id: formToObject('myFormId');
  • Using the actual DOM Node reference: formToObject(document.getElementById('myFormId'));

Resulted value:

{
  "saveSettings": "Save",
  "name": "Serban",
  "race": "orc",
  "settings": {
     "input": "keyboard",
     "video": {
        "resolution": "1024x768",
        "vsync": "on"
     }
  }
}

Good to know:

  1. If <form> fields are found, but they lack of name attribute property, the result will be {} (empty object).
  2. If <form> contains only disabled fields, the result will be {} (empty object). If you force includeDisabledFields then key:value pairs will be returned.
  3. An empty <form> will throw an Error.
  4. In case of an error like non-existing form or invalid selector, an Error will be thrown.

Options

Browser support

IE 8, Firefox 3.5, Chrome, Safari, Opera 10, every mobile browser.

Example