how take values from JSON.stringify($('form').serialize())

How to take values from JSON.stringify($('form').serialize())

If you want to collect form data and turn it into a JSON string, you can use the jQuery serialize method and then JSON.stringify it.

Method 1:

First, use jQuery to select the form element and serialize it into a string:

var formdata = $('form').serialize();

Then, use JSON.stringify to turn it into a JSON string:

var jsondata = JSON.stringify(formdata);

You can then output the JSON string to a div element:

<div id="output"></div>

In your JavaScript, select the output div and set its text to the JSON string:


Method 2:

A more concise way to achieve this is to combine the two steps into one using jQuery's map function:

var formdata = $('form').serializeArray();
var jsondata = JSON.stringify($.map(formdata, function(obj){return {[]: obj.value}}));

This code first serializes the form data into an array using serializeArray. Then, it uses jQuery's map function to map each element of the array into an object with the element's name as the key and its value as the value. Finally, it JSON stringifies the resulting array of objects.

The outputting process is the same as in Method 1.

Method 3:

If you want to use plain JavaScript instead of jQuery, you can use the FormData object:

var formdata = new FormData(document.querySelector('form'));
var jsondata = {};
for (var pair of formdata.entries()) {
  jsondata[pair[0]] = pair[1];
jsondata = JSON.stringify(jsondata);

This code creates a new FormData object from the form element, and then iterates through its entries to construct a JSON object. Finally, it JSON stringifies the object.

The outputting process is the same as in Method 1.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]