Skip to content

Repository files navigation

form-serialize Build Status

serialize form fields to submit a form over ajax

install

npm install form-serialize

use

form-serialize supports two output formats, url encoded (default) or hash (js objects).

Lets serialize the following html form:

<formid="example-form"><inputtype="text" name="foo" value="bar"/><inputtype="submit" value="do it!"/></form>
varserialize=require('form-serialize');varform=document.querySelector('#example-form');varstr=serialize(form);// str -> "foo=bar"varobj=serialize(form,{hash: true});// obj -> { foo: 'bar' }

api

serialize(form [, options])

Returns a serialized form of a HTMLForm element. Output is determined by the serializer used. Default serializer is url-encoded.

argtypedesc
formHTMLFormmust be an HTMLForm element
optionsObjectoptional options object

options

optiontypedefaultdesc
hashbooleanfalseif true, the hash serializer will be used for serializer option
serializerfunctionurl-encodingoverride the default serializer (hash or url-encoding)
disabledbooleanfalseif true, disabled fields will also be serialized

custom serializer

Serializers take 3 arguments: result, key, value and should return a newly updated result.

See the example serializers in the index.js source file.

notes

only successfull control form fields are serialized (with the exception of disabled fields if disabled option is set)

multiselect fields with more than one value will result in an array of values in the hash output mode using the default hash serializer

explicit array fields

Fields who's name ends with [] are always serialized as an array field in hash output mode using the default hash serializer. The field name also gets the brackets removed from its name.

This does not affect url-encoding mode output in any way.

<formid="example-form"><inputtype="checkbox" name="foo[]" value="bar" checked/><inputtype="checkbox" name="foo[]" value="baz" /><inputtype="submit" value="do it!"/></form>
varserialize=require('form-serialize');varform=document.querySelector('#example-form');varobj=serialize(form,{hash: true});// obj -> { foo: ['bar'] }varstr=serialize(form);// str -> "foo[]=bar"

references

This module is based on ideas from jQuery serialize and the Form.serialize method from the prototype library

license

MIT

About

serialize html forms

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages