1. React Js Serialize Form
  2. Js Serialize Form Ajax
  3. Js Serialize Formdata
  4. Vue Js Serialize Form
  5. Vue Js Serialize Form Data
  6. Js Serialize Form On Submit
  1. I was having some issues using the above solutions with an 'associative array' type object. These solutions seem to preserve the values, but they do not preserve the actual names of the objects that those values are associated with, which can cause some issues.
  2. Oct 29, 2018  How to serialize form data with vanilla JS Today, I’m going to teach you how to get form data as a string of encoded key/value pairs. This is useful when you want to submit a form with Ajax or save the data for use later. A helper function. The serialize helper function makes this really easy. Pass in the form element, and it spits out a.
Active1 month ago

Convert form data to JavaScript object with jQuery Anyway, it is very confusing your situation caused by this lack of details. If you're using a web server (non-local) this code can be wrong if you forget to setup the actual jquery link.

How do I convert all elements of my form to a JavaScript object?

I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by $('#formid').serialize();, nor do I want the map returned by $('#formid').serializeArray();


48 Answers

12 next

serializeArray already does exactly that. You just need to massage the data into your required format:

Watch out for hidden fields which have the same name as real inputs as they will get overwritten.


Current source is on GitHub and bower.

$ bower install jquery-serialize-object

The following code is now deprecated.

The following code can take work with all sorts of input names; and handle them just as you'd expect.

For example:

Usage

The Sorcery (JavaScript)



A fixed version of Tobias Cohen's solution. This one correctly handles falsy values like 0 and '.

And a CoffeeScript version for your coding convenience:


I like using Array.prototype.reduce because it's a one-liner, and it doesn't rely on Underscore.js or the like:

This is similar to the answer using Array.prototype.map, but you don't need to clutter up your scope with an additional object variable. One-stop shopping.

IMPORTANT NOTE: Forms with inputs that have duplicate name attributes are valid HTML, and is actually a common approach. Using any of the answers in this thread will be inappropriate in that case (since object keys must be unique).


All of these answers seemed so over the top to me. There's something to be said for simplicity. As long as all your form inputs have the name attribute set this should work just jim dandy.


If you are using Underscore.js you can use the relatively concise:


There really is no way to do this without examining each of the elements. What you really want to know is 'has someone else already written a method that converts a form to a JSON object?' Something like the following should work -- note that it will only give you the form elements that would be returned via a POST (must have a name). This is not tested.


Ok, I know this already has a highly upvoted answer, but another similar question was asked recently, and I was directed to this question as well. I'd like to offer my solution as well, because it offers an advantage over the accepted solution: You can include disabled form elements (which is sometimes important, depending on how your UI functions)

Here is my answer from the other SO question:

Initially, we were using jQuery's serializeArray() method, but that does not include form elements that are disabled. We will often disable form elements that are 'sync'd' to other sources on the page, but we still need to include the data in our serialized object. So serializeArray() is out. We used the :input selector to get all input elements (both enabled and disabled) in a given container, and then $.map() to create our object.

Note that for this to work, each of your inputs will need a name attribute, which will be the name of the property of the resulting object.

That is actually slightly modified from what we used. We needed to create an object that was structured as a .NET IDictionary, so we used this: (I provide it here in case it's useful)

I like both of these solutions, because they are simple uses of the $.map() function, and you have complete control over your selector (so, which elements you end up including in your resulting object). Also, no extra plugin required. Plain old jQuery.


This function should handle multidimensional arrays along with multiple elements with the same name.

I've been using it for a couple years so far:



One-liner (no dependencies other than jQuery), uses fixed object binding for function passsed to map method.

What it does?

suitable for progressive web apps (one can easily support both regular form submit action as well as ajax requests)


With all Given Answer there some problem which is., If input name as array like name[key], but it will generate like this

For Example : If i have form like this.

Serialize form data

Then It will Generate Object like this with all given Answer.

But it have to Generate like below,anyone want to get like this as below.

Then Try this below js code.



Simplicity is best here. I've used a simple string replace with a regular expression, and they worked like a charm thus far. I am not a regular expression expert, but I bet you can even populate very complex objects.



Using maček's solution, I modified it to work with the way ASP.NET MVC handles their nested/complex objects on the same form. All you have to do is modify the validate piece to this:

This will match and then correctly map elements with names like:

And


I found a problem with Tobias Cohen's code (I don't have enough points to comment on it directly), which otherwise works for me. If you have two select options with the same name, both with value=', the original code will produce 'name':' instead of 'name':[',']

I think this can fixed by adding ' o[this.name] '' to the first if condition:


React Js Serialize Form

the simplest and most accurate way i found for this problem was to use bbq plugin or this one (which is about 0.5K bytes size).

it also works with multi dimensional arrays.


There is a plugin to do just that for jQuery, jquery.serializeJSON. I have used it successfully on a few projects now. It works like a charm.


I prefer this approach because: you don't have to iterate over 2 collections, you can get at things other than 'name' and 'value' if you need to, and you can sanitize your values before you store them in the object (if you have default values that you don't wish to store, for example).

Use like so:

Only tested in Firefox.


Eset nod32 antivirus serial key 2018 to 2020. Turn anything into an object (not unit tested)

The output of test:

on

will yield:


I found a problem with the selected solution.

When using forms that have array based names the jQuery serializeArray() function actually dies.

I have a PHP framework that uses array-based field names to allow for the same form to be put onto the same page multiple times in multiple views. This can be handy to put both add, edit and delete on the same page without conflicting form models.

Since I wanted to seralize the forms without having to take this absolute base functionality out I decided to write my own seralizeArray():

Please note: This also works outside of form submit() so if an error occurs in the rest of your code the form won't submit if you place on a link button saying 'save changes'.

Also note that this function should never be used to validate the form only to gather the data to send to the server-side for validation. Using such weak and mass-assigned code WILL cause XSS, etc.


I had the same problem lately and came out with this .toJSON jQuery plugin which converts a form into a JSON object with the same structure. This is also expecially useful for dynamically generated forms where you want to let your user add more fields in specific places.

The point is you may actually want to build a form so that it has a structure itself, so let's say you want to make a form where the user inserts his favourite places in town: you can imagine this form to represent a <places>.</places> XML element containing a list of places the user likes thus a list of <place>.</place> elements each one containing for example a <name>.</name> element, a <type>.</type> element and then a list of <activity>.</activity> elements to represent the activities you can perform in such a place. So your XML structure would be like this:

How cool would it be to have a JSON object out of this which would represent this exact structure so you'll be able to either:

  • Store this object as it is in any CouchDB-like database
  • Read it from your $_POST[] server side and retrive a correctly nested array you can then semantically manipulate
  • Use some server-side script to convert it into a well-formed XML file (even if you don't know its exact structure a-priori)
  • Just somehow use it as it is in any Node.js-like server script

OK, so now we need to think how a form can represent an XML file.

Of course the <form> tag is the root, but then we have that <place> element which is a container and not a data element itself, so we cannot use an input tag for it.

Here's where the <fieldset> tag comes in handy! We'll use <fieldset> tags to represent all container elements in our form/XML representation and so getting to a result like this:

As you can see in this form, we're breaking the rule of unique names, but this is OK because they'll be converted into an array of element thus they'll be referenced only by their index inside the array.

At this point you can see how there's no name='array[]' like name inside the form and everything is pretty, simple and semantic.

Now we want this form to be converted into a JSON object which will look like this:

To do this I have developed this jQuery plugin here which someone helped optimizing in this Code Review thread and looks like this:

I also made this one blog post to explain this more. En 1090 1 pdf.

This converts everything in a form to JSON (even radio and check boxes) and all you'll have left to do is call

I know there's plenty of ways to convert forms into JSON objects and sure .serialize() and .serializeArray() work great in most cases and are mostly intended to be used, but I think this whole idea of writing a form as an XML structure with meaningful names and converting it into a well-formed JSON object is worth the try, also the fact you can add same-name input tags without worrying is very useful if you need to retrive dynamically generated forms data.

I hope this helps someone!


I coded a form to a multidimensional JavaScript object myself to use it in production. The result is https://github.com/serbanghita/formToObject.js.


Js Serialize Form Ajax

I like samuels version, but I believe it has a small error. Normally JSON is sent as

{'coreSKU':'PCGUYJS','name_de':'whatever',.

NOT as

Js Serialize Formdata

[{'coreSKU':'PCGUYJS'},{'name_de':'whatever'},.

so the function IMO should read:

and to wrap it in data array (as commonly expected, too), and finally send it as astringApp.stringify( {data:App.toJson( '#cropform :input' )} )

For the stringify look at Question 3593046 for the lean version, at json2.js for the every-eventuality-covered version. That should cover it all :)


For a quick, modern solution, use the JSONify jQuery plugin. The example below is taken verbatim from the GitHub README. All credit to Kushal Pandya, author of the plugin.

Given:

Running:

Produces:

If you want to do a jQuery POST with this JSON object:

Vue Js Serialize Form



Vue Js Serialize Form Data

Another answer

FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData


I wouldn't use this on a live site due to XSS attacks and probably plenty of other issues, but here's a quick example of what you could do:


protected by Josh CrozierMay 30 '14 at 20:18

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?

Js Serialize Form On Submit

Not the answer you're looking for? Browse other questions tagged javascriptjqueryjsonserialization or ask your own question.