In this tutorial we will create a How to Convert HTML Inputs to JSON Object in JavaScript. This tutorial purpose is to teach you how to convert your html inputs into JSON object. This will tackle all the basic function that will convert your form data. I will provide a sample program to show the actual coding of this tutorial.
This tutorial is simple and easy to understand just follow the instruction I provided and you can do it without a problem. This program can be use to any system or application if you want to convert your form data into a readable JSON object. I will give my best to provide you the easiest way of creating this program Convert form data into JSON Object. So let's do the coding.
This is the link for the template that i used for the layout design https://getbootstrap.com/.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> </div> </nav> <div class="col-md-6 well"> <hr style="border-top:1px dotted #ccc;"/> <div class="col-md-8"> </div> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" id="firstname"/> </div> <div class="form-group"> <input type="text" class="form-control" id="lastname"/> </div> </div> </div> </body> </html>
let member = JSON.parse('{"members":[]}'); function displayJson(firstname, lastname, json){ document.getElementById('result').innerHTML = "<pre>"+json+"</pre>"; firstname.value = ""; lastname.value = ""; } function convertToJson(){ let firstname = document.getElementById('firstname'); let lastname = document.getElementById('lastname'); if(firstname.value == "" || lastname.value == ""){ alert("Please complete the required field!"); }else{ let str = '{"firstname": "'+firstname.value+'", "lastname": "'+lastname.value+'"}'; member['members'].push(str); let stringify = JSON.stringify(member, null, ' '); let json = stringify.replace(/\\/g, ''); displayJson(firstname, lastname, json); } }
In the code above we create a method called convertToJson(), this function will convert the html form data into JSON object. We bind first the two input into variables then create a JSON structure with the two variables in it called str. We push the structure to array object and then we use JSON.stringify() function to make turn the array into JSON object.
The How to Convert HTML Inputs to JSON Object in JavaScript source code that I provide can be download below. Please kindly click the download button.
There you have it we successfully created How to Remove Element from an Array in JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for JavaScript Language