# form2js _Convenient way to collect **structured** form data into JavaScript object._ Example: http://form2js.googlecode.com/hg/example/test.html If you have any questions/suggestions or find out something weird or illogical - feel free to post an issue. Because everythins is better with jQuery, jQuery plugin added, check out jquery.toObject.js =) **Warning!** form2object.js and form2object function renamed to form2js.js and form2js respectively. Old names are in v1.0 tag. ## Details Structure of resulting object defined by _name_ attribute of form fields. See examples below. This is **not** a serialization library. Library used in example for JSON serialization is http://www.json.org/js.html All this library doing is collecting form data and putting it in javascript object (obviously you can get JSON/XML/etc string by serializing it, but it's not an only purpose). ## Usage form2js(rootNode, delimiter, skipEmpty, nodeCallback, useIdIfEmptyName) Values of all inputs under the _rootNode_ will be collected into one object (skipping empty inputs if _skipEmpty_ not false). ### Objects/nested objects Structure of resulting object defined in _name_ attributes of form fields (or _id_ if _name_ is empty and _useIdIfEmptyName_ parameter set to _true_), _delimiter_ is "." (dot) by default, but can be changed. becomes { "person" : { "name" : { "first" : "John", "last" : "Doe" } } } ### Arrays Several fields with the same name with brackets defines array of values. becomes { "person" : { "favFood" : [ "steak", "chicken" ] } } ### Arrays of objects/nested objects Same index means same item in resulting array. Index doesn't specify order (order of appearance in document will be used).
Give us your five friends' names and emails
becomes { "person" : { "friends" : [ { "email" : "agent.smith@example.com", "name" : "Smith Agent" }, { "email" : "n3o@example.com", "name" : "Thomas A. Anderson" } ] } } ### Ruby-style notation If array index starts with [a-zA-Z_], it will be treated as field of object.
Ruby-style test
will give us { "ruby": { "field1": { "foo": "baz", "bar": "qux" }, "field2": { "foo": "baz", "bar": "qux" } } } ### Custom fields You can implement custom nodeCallback function (passed as 4th parameter to form2object()) to extract custom data:
Date of birth:
using _processDate()_ callback _formData_ will contain { "person": { "dateOfBirth": "2011-01-12" } } ## Why not to use jQuery .serializeArray() or similar functions in other frameworks instead? .serializeArray() works a bit different. It makes this structure from markup in "Arrays of objects/nested objects" example: [ { "person.friends[0].email" : "agent.smith@example.com" }, { "person.friends[0].name" : "Smith Agent" }, { "person.friends[1].email" : "n3o@example.com" }, { "person.friends[1].name" : "Thomas A. Anderson" } ]