Ads

Thursday 21 August 2014

Serialize Object - Converts HTML form into JavaScript object

Download   Demo


Serialize Object is a jquery plugin that Converts HTML form into JavaScript object


Adds the method serializeObject to jQuery, to perform complex form serialization into JavaScript objects.


The current implementation relies in jQuery.serializeArray() to grab the form attributes and then create the object using the input name attributes.


This means it will serialize the inputs that are supported by .serializeArray(), that use the standard W3C rules for successful controls to determine which inputs should be included; in particular:


  • The input cannot be disabled and must contain a name attribute.

  • No submit button value is serialized since the form is not submitted using a button.

  • Data from <input type=”file”> inputs are not serialized.

1. INCLUDE JS FILES


<script src=”jquery.min.js”></script>

<script src=”jquery.serialize-object.min.js”></script>


2. HTML


<form id=”contact”>

<input name=”user[email]” value=”jsmith@example.com”>

<input name=”user[pets][]” type=”checkbox” value=”cat” checked>

<input name=”user[pets][]” type=”checkbox” value=”dog” checked>

<input name=”user[pets][]” type=”checkbox” value=”bird”>

<input type=”submit”>

</form>


3. JAVASCRIPT


.serializeObject — serializes the selected form into a JavaScript object


$(‘form#contact’).serializeObject();

//=> user: email: “jsmith@example.com”, pets: ["cat", "dog"]


.serializeJSON — serializes the selected form into JSON


$(‘form#contact’).serializeJSON();

//=> ‘“user”:“email”:”jsmith@example.com”,”pets”:["cat","dog"]’


FormSerializer.patterns — modify the patterns used to match field names


Many of you have requested to allow – in field names or use . to nest keys. You can now configure these to your heart’s content.


$.extend(FormSerializer.patterns, (?=\[\])/gi,

named:    /^[a-z0-9_-]+$/i

);


$.extend(FormSerializer.patterns,

validate: /^[a-z][a-z0-9_]*(?:\.[a-z0-9_]+)*(?:\[\])?$/i

);


Validating and Key parsing


validate — only valid input names will be serialized; invalid names will be skipped


key — this pattern parses all “keys” from the input name; You will want to use /g as a modifier with this regexp.


Key styles


push — pushe a value to an array


<input name=”foo[]” value=”a”>

<input name=”foo[]” value=”b”>


$(“form”).serializeObject();

//=> foo: [a, b]


fixed — add a value to an array at a specified index


<input name=”foo[2]” value=”a”>

<input name=”foo[4]” value=”b”>


$(“form”).serializeObject();

//=> foo: [, , "a", , "b"]


named — adds a value to the specified key


<input name=”foo[bar]” value=”a”>

<input name=”foo[bof]” value=”b”>

<input name=”hello” value=”world”>


$(“form”).serializeObject();

//=> foo: bar: “a”, bof: “b”, hello: “world”



Serialize Object - Converts HTML form into JavaScript object

No comments:

Post a Comment