JavaScript Form To JSON

JavaScript Form To Jason
Project: JavaScript: serialize a form as JSON
Author: Gabriele Romanato
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to convert form data to JSON. It defines a function called toJSONString that converts the values of form elements into a JSON string. It then attaches an event listener to the document that listens for when the DOM is loaded.

Once the DOM is loaded, the code assigns the test form element to a variable and assigns the output element to another variable.

Finally, the code attaches a submit event listener to the test form element, which prevents the form from submitting normally and instead calls the toJSONString function to convert the form data into a JSON string.

How to Convert Form Data to JSON in JavaScript

First of all, load the following assets into the head tag of your HTML document. (optional)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel='stylesheet' href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>

Now, create a form in HTML as follows:

<form id="test" action="#" method="post">
    <div class="form-group">
        <label for="name">Name</label>
        <input class="form-control" type="text" name="name" id="name" />
    </div>
    <div class="form-group">
    	<label for="check">Check if you like JavaScript</label>
    	<input type="checkbox" name="check" value="yes" />
    </div>
    <div class="form-group">
    	<label for="select">Select your favorite JavaScript framework</label>
    	<select name="select" class="form-control">
    		<option value="none" selected="selected">None</option>
    		<option value="jquery">jQuery</option>
    		<option value="angularjs">Angular</option>
    		<option value="mine">Mine, of course!</option>
    	</select>

    </div>
    <div class="form-group">
    	<label for="message">Leave a message</label>
    	<textarea class="form-control" name="message" rows="15" cols="30"></textarea>
    </div>
    <div class="form-group">
        <label for="email">Email</label>
        <input class="form-control" type="text" name="email" id="email" />
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input class="form-control" type="password" name="password" id="password" />
    </div>
    <p>
        <input type="submit" value="Send" class="btn btn-primary btn-block" />
    </p>
</form>	
<pre id="output"></pre>

Style the form using the following CSS. These CSS styles are optional, you can define your own according to your needs.

body {
  margin: 2em auto;
  max-width: 600px;
}

form div {
    margin-bottom: 0.5em;
}
.cd__main{
display: block !important;
}
form div label, form div input {
    display: block;
    margin-bottom: 0.3em;
}

Finally, add the following JavaScript function:

(function() {
	function toJSONString( form ) {
		var obj = {};
		var elements = form.querySelectorAll( "input, select, textarea" );
		for( var i = 0; i < elements.length; ++i ) {
			var element = elements[i];
			var name = element.name;
			var value = element.value;

			if( name ) {
				obj[ name ] = value;
			}
		}

		return JSON.stringify( obj );
	}

	document.addEventListener( "DOMContentLoaded", function() {
		var form = document.getElementById( "test" );
		var output = document.getElementById( "output" );
		form.addEventListener( "submit", function( e ) {
			e.preventDefault();
			var json = toJSONString( this );
			output.innerHTML = json;

		}, false);

	});

})();

That’s all! hopefully, you have successfully created JavaScript functionality to convert form data to JSON. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *