I\'m having a bit of trouble serializing a form
The accepted answer works great if your form doesn't have checkboxes or radio buttons. Since groups of those all have the same name attribute, you need to create an array value inside the object. So for html like:
<input type="checkbox" value="1" name="the-checkbox">
<input type="checkbox" value="1" name="the-checkbox">
<input type="checkbox" value="1" name="the-checkbox">
You'll get:
{the-checkbox:['1', '2', '3']}
This bit of code handles everything nicely.
/*!
* jQuery serializeObject - v0.2 - 1/20/2010
* http://benalman.com/projects/jquery-misc-plugins/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
$.fn.serializeObject = function(){
var obj = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
})(jQuery);
Usage
$(form).serializeObject();
You can do this quite simply using .reduce()
and destructuring assignment:
const arr = $('form').serializeArray(); // get the array
const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object
Example:
$('form').on('submit', function(e) {
e.preventDefault(); // only used for example (so you can see output in console);
const arr = $(this).serializeArray(); // get the array
const data = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}),{}); // form the object
console.log(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" placeholder="username" name="username"/>
<input type="email" placeholder="email" name="email"/>
<input type="submit" />
</form>
You can make a custom function.
var complex = $(form).serialize(); // name1=value1&name2=value2
var json = toSimpleJson(complex); // {"name1":"value1", "name2":"value2"}
function toSimpleJson(serializedData) {
var ar1 = serializedData.split("&");
var json = "{";
for (var i = 0; i<ar1.length; i++) {
var ar2 = ar1[i].split("=");
json += i > 0 ? ", " : "";
json += "\"" + ar2[0] + "\" : ";
json += "\"" + (ar2.length < 2 ? "" : ar2[1]) + "\"";
}
json += "}";
return json;
}
new_obj = {}
$.each($(form).serializeArray(), function(i, obj) { new_obj[obj.name] = obj.value })
your data is in new_obj
Here is some modernization of Hollister's code.
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
$.fn.serializeObject = function(){
var obj = {},
names = {};
$.each( this.serializeArray(), function(i,o){
var n = o.name,
v = o.value;
if ( n.includes( '[]' ) ) {
names.n = !names.n ? 1 : names.n+1;
var indx = names.n - 1;
n = n.replace( '[]', '[' + indx + ']' );
}
obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v )
: [ obj[n], v ];
});
return obj;
};
})(jQuery);
In case you need field names as myvar[]
for checkboxes.
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};