danheberden / jquery-serializeform Goto Github PK
View Code? Open in Web Editor NEWjQuery plugin to serialize form elements into an object
License: MIT License
jQuery plugin to serialize form elements into an object
License: MIT License
jQuery's official .serialize() and .serializeArray() functions return the serialization result even if you provide an :input object or a collection of those, which is very useful sometimes. Currently, .serializeObject() only works if you provide a form object or any object that contains :input objects. In order to make .serializeObject() work like the official jQuery functions mentioned before, you folks just need to modify a small part of the code. I propose the following:
/*
serializeObject
Copyright (c) 2012 Dan Heberden
Licensed under the MIT, GPL licenses.
*/
(function( $ ){
$.fn.serializeObject = function() {
if ( this.length < 1) {
return false;
}
var $el = this;
var data = {};
var lookup = data; //current reference of data
if($el.is(':input')){
$inputElements = $el.filter( ':input[type!="checkbox"][type!="radio"], input:checked' );
}else{
$inputElements = $el.find( ':input[type!="checkbox"][type!="radio"], input:checked' );
}
$inputElements.each( function() {
// data[a][b] becomes [ data, a, b ]
var named = this.name.replace(/[([^]]+)?]/g, ',$1').split(',');
var cap = named.length - 1;
// Ensure that only elements with valid `name` properties will be serialized
if ( named[ 0 ] ) {
for ( var i = 0; i < cap; i++ ) {
// move down the tree - create objects or array if necessary
lookup = lookup[ named[i] ] = lookup[ named[i] ] ||
( named[ i + 1 ] === "" ? [] : {} );
}
// at the end, push or assign the value
if ( lookup.length !== undefined ) {
lookup.push( $( this ).val() );
}else {
lookup[ named[ cap ] ] = $( this ).val();
}
// assign the reference back to root
lookup = data;
}
});
return data;
};
}( jQuery ));
This shouldn't rely on jQuery - it should be able to take an array/nodeList of dom elements to look through as well and add itself as a $.fn method if necessary. As for exposing globally, making it an AMD module would be totes hot.
Hi Dan,
First of all Great plugin Thanks for sharing !
I am banging my head against the wall for the last 1 hour and I could't figure it out...
Is it possible by using only the input fields to create an object array something like:
{block: [
{
room: "office",
people: [
{ first_name: "Jane", last_name: "Doe"},
{ first_name: "John", last_name: "Doe" }
]
},
{
room: "cantine",
people: [
{ first_name: "Juba", last_name: "Laba"},
{ first_name: "Bono", last_name: "Boo" }
]
}
]}
Thanks in advance,
Cheers,
Guby
Hi,
The disabled inputs are also added in the result.
For instance this input :
Will generate :
{
"test" : ""
}
This is unexpected since in a simple post this inputs would be excluded.
Regards,
Hi,
Which license is this wonderful piece of code released under?
//Kenneth
Zero-indexed array names are not converted to an array. For example:
<input type="text" name="foo[0]" value="foo0">
<input type="text" name="foo[1]" value="foo1">
Is converted to:
"foo": {
"0": "foo0",
"1": "foo1"
}
The expected format would be:
"foo": [
"foo0",
"foo1"
]
Hey,
I was using your jQuery plugin and have encountered this weird behaviour.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.serialize-object.js"></script>
</head>
<body>
<form id="new_form">
User Name:
<input type="text" name="agent_signup[user_name]">
<br>
User Email:
<input type="text" name="agent_signup[user_user_emails_attributes[0][email]]">
<br>
Agent Role
<input type="checkbox" name="agent_signup[role_ids][]" value="1">Account Administrator
<input type="checkbox" name="agent_signup[role_ids][]" value="2">Administrator
<input type="checkbox" name="agent_signup[role_ids][]" value="4">Agent
<input type="checkbox" name="agent_signup[role_ids][]" value="3">Supervisor
<button>Submit</button>
</form>
</body>
</html>
To serialize the form, I ran
$("#new_form").serializeObject()
The returned object was
"{"agent_signup":{"user_name":"tushar","user_user_emails_attributes[0":{"email]":"[email protected]"},"role_ids":["1","4"]}}"
whereas the expected object is
"{"agent_signup":{"user_name":"tushar","user_user_emails_attributes":{"0":{"email":"[email protected]"}},"role_ids":["1","4"]}}"
Allow options to output serialized data as either array
, JSON
or url params
formats
Assuming you're following the pattern used by jQuery.fn.serialize(), elements without a name property should be ignored
Test case: http://jsfiddle.net/rwaldron/vqwrY/
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.