How to Convert HTML Form Field Values to JSON Object Using Javascript and jQuery Full Tutorial For Beginners

How to Convert HTML Form Field Values to JSON Object Using Javascript and jQuery Full Tutorial For Beginners

 

Welcome folks today in this blog post we will be converting html form field values to json object using javascript and jquery. All the source code of the examples are given below.

 

 

Get Started

 

 

In order to get started you need to download and install form-to-json library

 

official github repository

 

 

 

 

 

Now make a index.html file and copy paste the following code to include the libraries

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form to JSON with jQuery</title>

    <link rel="stylesheet" href="./css/form-to-json-v1.0.0.css" type="text/css">
</head>
<body>
    <h1>Sample form:</h1>
    <p>* marked fields are required</p>

    <form id="myForm">
        <div class="form-row">
            <label for="firstname">First Name: *</label><br />
            <input type="text" name="firstname" id="firstname" class="form-input-field" placeholder="First Name" required>
        </div>
        <div class="form-row">
            <label for="lastname">Last Name: *</label><br />
            <input type="text" name="lastname" id="lastname" class="form-input-field" placeholder="Last Name" required>
        </div>
        <div class="form-row">
            <label for="email">Email: *</label><br />
            <input type="email" name="email" id="email" class="form-input-field" placeholder="Email" required>
        </div>
        <div class="form-row">
            <label for="phone">Phone: *</label><br />
            <input type="phone" name="phone" id="phone" class="form-input-field" placeholder="Phone" required>
        </div>
        <div class="form-row">
            <label form="subject">Subject: *</label><br />
            <input type="text" name="subject" id="subject" class="form-input-field" placeholder="Subject" required>
        </div>
        <div class="form-row">
            <label for="comments">Comments:</label><br />
            <textarea name="comments" id="comments" class="form-input-field" rows="6"></textarea>
        </div>
        <div class="form-row">
            <input type="submit" name="submit" value="Submit" class="form-submit-btn">
        </div>
    </form>

    <div class="results">
        <p class="result-json-output"></p>
    </div>


    <script src="./includes/js/jquery-3.5.1.min.js"></script>
    <script src="./includes/js/form-to-json-v1.0.0.js"></script>
    <script src="./includes/js/script.js"></script>
</body>
</html>

 

 

 

Now make a form-to-json-v1.0.0.js file and copy paste the following code

 

 

/**
 * Name: Form to JSON
 * Description: Create JSON object from a form submission using jQuery
 * Version: 1.0.0
 * Author: Shrikumar Infotech
 * Author URI: dev@shrikumarinfotech.com
 * License: MIT
 * Lincense URI: https://opensource.org/licenses/MIT
 */

'use strict';

jQuery(function( $ ){
    // plugin function
    $.fn.formToJson = function( resultContainer ){
        // console.log('this is from plugin');

        // define form
        const form = this;
        // define display target from parameter
        // if(resultContainer != undefined){
        //     const displayResultTarget = resultContainer;
        // }
        // console.log(resultContainer);

        // define submitted data
        let submittedData = [];

        // define form data structure
        let formData = {
            id: Number,
            firstname: String,
            lastname: String,
            email: String,
            phone: Number,
            subject: String,
            comments: String,
            createdDate: String
        };
        // define json data for output
        let jsonOutputData = Object.create(formData);

        // form submission function
        $(form).submit(function( event ){
            event.preventDefault();

            // console.log($(form).serialize());
            // run sort data function
            sortData( $(form).serialize() );

            // run json data function
            jsonData();

            // display json data
            outputData();

            // reset data
            resetData();

        });

        // sort data function
        function sortData( data ){
            // sanity check
            if(data != undefined){
                // regular expessions
                const regxSpace = /(?:%20)/gi;
                const regxEmail = /(?:%40)/gi;
                const regxLineBreak = /(?:%0D%0A)/gi;
                // save data by replacing with regx and split with '&' as parts
                let sortedData = data.replace(regxSpace, ' ').replace(regxEmail, '@').replace(regxLineBreak, '\n').split('&');
                // iterate through sortedData and save as array into submittedData
                $(sortedData).each(function(index, element){
                    submittedData.push(element.split('='));
                });

                // console.log(submittedData);
            }
        };

        // json data function
        function jsonData(){
            // sanity check
            if(submittedData != undefined || submittedData != null){
                // create JSON data
                $(submittedData).promise().done(function(){
                    // save json data
                    jsonOutputData.id = Math.random();
                    jsonOutputData.firstname = submittedData[0][1];
                    jsonOutputData.lastname = submittedData[1][1];
                    jsonOutputData.email = submittedData[2][1];
                    jsonOutputData.phone = submittedData[3][1];
                    jsonOutputData.subject = submittedData[4][1];
                    jsonOutputData.comments = submittedData[5][1],
                    jsonOutputData.createdDate = Date.now()
                });
            }
        };

        // output data
        function outputData(){
            // stingify jsonOutputData for output
            let stringifyJsonData = JSON.stringify(jsonOutputData);

            // check if output target is provided
            if(resultContainer !== undefined || resultContainer !== null){
                $(jsonOutputData).promise().done(function(){
                    $(resultContainer).html( stringifyJsonData );
                    // return stringifyJsonData;
                    console.log(stringifyJsonData); // log the JSON data
                });
            }
            else{
                // else just return the JSON data
                console.log('resultContainer undefined');
                return stringifyJsonData;
            }
        }

        // reset data
        function resetData(){
            // reset all data
            submittedData = [];
            jsonOutputData = {};
        }
        
    }
}(jQuery));

 

See also  Build a TMDb API (themoviedb) Movie Info Finder Web App in Vanilla Javascript Full Project For Beginners

 

Now make a form-to-json-v1.0.0.css file and copy paste the following code

 

 

/**
 * Name: Form to JSON
 * Description: Create JSON object from a form submission using jQuery
 * Version: 1.0.0
 * Author: Shrikumar Infotech
 * Author URI: dev@shrikumarinfotech.com
 * License: MIT
 * Lincense URI: https://opensource.org/licenses/MIT
 */
html {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 67.5%;
}

* {
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
}

body {
  font-size: 1.6rem;
  color: #000000;
  background-color: #ffffff;
}

label {
  font-weight: bold;
}

.form-row {
  margin-top: 5px;
  margin-bottom: 5px;
}

.form-input-field {
  width: 350px;
  padding: 4px;
  font-size: 1.4rem;
}

.form-submit-btn {
  padding: 10px 25px;
  color: #ffffff;
  background-color: #3f3f3f;
  border-radius: 0;
  border: 0;
  -webkit-box-shadow: none;
          box-shadow: none;
  cursor: pointer;
}

.form-submit-btn:hover {
  color: #ffffff;
  background-color: #000000;
}

.results .result-json-output {
  color: #0066ff;
}
/*# sourceMappingURL=form-to-json-v1.0.0.css.map */

 

See also  Build a Youtube Video Thumbnail Extractor or Grabber Web App in Browser Using HTML5 CSS3 and Javascript Full Project For Beginners

 

And now make a script.js file and copy paste the following code

 

 

/**
 * Name: Form to JSON
 * Description: Create JSON object from a form submission using jQuery
 * Version: 1.0.0
 * Author: Shrikumar Infotech
 * Author URI: dev@shrikumarinfotech.com
 * License: MIT
 * Lincense URI: https://opensource.org/licenses/MIT
 */

'use strict';

jQuery.noConflict();
jQuery(document).ready(function( $ ){

    // usage: 2
    $('#myForm').formToJson('.result-json-output');

});

 

 

Screenshot

 

 

 

 

 

 

Leave a Reply