Skip to content

Latest commit

 

History

History
85 lines (69 loc) · 3.6 KB

README.md

File metadata and controls

85 lines (69 loc) · 3.6 KB

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($('test'), 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.
jQuery.serializeJSON $('#test').serializeJSON() Adds the method .serializeJSON() to jQuery, that serializes a form into a JavaScript Object with the same format as the default Ruby on Rails request params hash.
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 .