Convert Form Data To A JSON Object - formToJson.js

File Size: 3.7 KB
Views Total: 24119
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Convert Form Data To A JSON Object - formToJson.js

A super tiny form to JSON converter that makes it easier to serialize your current form data to a JavaScript/JSON objects containing field names & values.

How to use it:

1. Insert the minified version of the jQuery formToJson.js plugin after jQuery.

<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/formToJson.js"></script>

2. Serialize the form data to a JSON object. Note that each form field must have a unique name.

<form action="#" method="post">
  <input type="text" name="name" value="jQueryScript" />
  <input type="text" name="email" value="[email protected]" />
  <input type="text" name="url" value="https://www.jqueryscript.net" />
  <input type="submit" />
</form>
$("form").submit(function() {
  console.log($(this).formToJson());
  return false;
});

3. The output should be like these:

{
  "name":"jQueryScript",
  "email":"[email protected]",
  "url":"https://www.jqueryscript.net"
}

4. Convert the JSON object into a JSON string.

JSON.stringify($("form").formToJson())

This awesome jQuery plugin is developed by HasanQQ. For more Advanced Usages, please check the demo page or visit the official website.