form_to_object

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

npm install form_to_object
1 downloads in the last week
6 downloads in the last month

Ever wanted to convert a HTML form with all it's fields and values to a multi-dimensional JavaScript object?
Here is the easiest way, no 3rd party libraries, only vanilla JavaScript.

Comparison with other solutions
Prototype.js Form.serialize($('testForm'), true); Creates a JavaScript object but it's not multi-dimensional. In "settings[theme][type]": "dark" the key is a string. Tested with the latest built version from git, 1.7.1 throws errors.
jQuery $('#form').serializeArray()Creates a JavaScript array of objects, ready to be encoded as a JSON string. It takes in account the W3C rules for successful controls. Output is like [ Object, Object, Object ...]
Backbone.Syphon Backbone.Syphon.serialize(this); called in a Backbone.View Creates a multi-dimensional JavaScript object with only a few limitations. Has the ability to include/exclude fields.
dojo.formToObject domForm.toObject("myId") Depends on dojo framework. Disabled form elements, buttons, elements with just an id attribute but no name attribute, and other non-valued HTML elements are skipped.
jQuery.serializeObject $('form').serializeObject(); Plugin for jQuery.
jQuery.serializeForm $( '#test' ).serializeForm(); Plugin for jQuery.
plain JavaScript new formToObject('form') Creates a multi-dimensional JavaScript object with all the field names and values.
Browser support

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

Example
<!-- Include the method in your library. -->
<script src="/js/formToObject.js"></script>

Using the form's id value:

// console.log(myFormObj);
var myFormObj = new formToObject('myFormId');

Using the actual DOM Node:

var formNode  = document.getElementById('myFormId');
var myFormObj = new formToObject(formNode);
Screenshot

Contribute

Add an issue or fork the project and submit a pull request.
If this script helped you save a lot of developing time, I really appreciate any donations .

npm loves you