Get form data as an object using jQuery
Make data easy with Helical Insight.
Helical Insight is the world’s best open source business intelligence tool.
jQuery has an inbuilt method serializeArray
which returns the form data in the form of an array. But at times, we require the data in form of an object. For example, consider the following form:
<form id="myForm">
<input type="text" name="firstName" value="John">
<input type="text" name="lastName" value="Doe">
<input type="email" name="email" value="johndoe@example.com">
</form>
Now $('#myForm').serializeArray()
would result in the following:
[
{
name:"firstName",
value:"John"
},
{
name:"lastName",
value:"Doe"
},
{
name:"email",
value:"johndoe@example.com"
}
]
But sometimes we require it as an object:
{
firstName : "John",
lastName :"Doe",
email : "johndoe@example.com"
}
I know we can iterate over the serialized array and create the object but wouldn’t it be great if jQuery had this functionality built in?
I made a simple script that can be used to add this functionatily to jQuery:
jQuery.fn.serializeObject = function(){
var results = {},
arr = this.serializeArray();
for (var i = 0, len = arr.length; i < len; i++) {
obj = arr[i];
//Check if results have a property with given name
if (results.hasOwnProperty(obj.name)) {
//Check if given object is an array
if (!results[obj.name].push) {
results[obj.name] = [results[obj.name]];
}
results[obj.name].push(obj.value || '');
} else {
results[obj.name] = obj.value || '';
}
}
return results;
}
usage: $('#myForm').serializeObject()
Make data easy with Helical Insight.
Helical Insight is the world’s best open source business intelligence tool.
Note: The reason behind using serialzeArray
inside our snippet, despite the overhead is that it already handles multiselect(s) and checkboxes robustly, thus making our job easier.
Best Open Source Business Intelligence Software Helical Insight is Here