Ever wanted to convert a HTML form with all it's fields and values to a multi-dimensional JavaScript object?
<!-- Include script (~6kb) -->
<script src="src/formToObject.js"></script><!-- Include minified script (~2kb) -->
<script src="build/formToObject.min.js"></script>Using the form's id value:
var myFormObj = formToObject('myFormId');
console.log(myFormObj);Using the actual DOM Node:
var $formNode = document.getElementById('myFormId');
var myFormObj = formToObject($formNode);
console.log(myFormObj);Real case scenario with jQuery AJAX:
$.ajax({
'url': '/app/settings/save/',
'type': 'post',
'data': formToObject('saveSettingsForm'),
'success': function(r){
console.log(r);
}
});Prototype.js - 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.
Form.serialize($('test'), true);jQuery core - 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 ...]
$('#form').serializeArray()Backbone.Syphon - Creates a multi-dimensional JavaScript object with only a few limitations. Has the ability to include/exclude fields.
Backbone.Syphon.serialize(this); // called in a Backbone.Viewdojo.formToObject - 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.
domForm.toObject("myId")jQuery.serializeObject - Plugin for jQuery.
$('form').serializeObject();jQuery.serializeForm - Plugin for jQuery.
$('#test').serializeForm();jQuery.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.
$('#test').serializeJSON()plain JavaScript
formToObject('form')Creates a multi-dimensional JavaScript object with all the field names and values.
IE 8, Firefox 3.5, Chrome, Safari, Opera 10, every mobile browser.
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

