How to save user input to JSON object in HTML
Overview
JSON stands for JavaScript Object Notation. This format is commonly used to transfer the data in web applications. In this shot, we'll learn how to store the user input from HTML to JSON.
We'll use the JSON.stringify() method to convert the JavaScript object to JSON format.
Example
In this example, we'll get the input from HTML, store the data in a JavaScript object, and convert it to JSON.
Code example
//get references for text input and button fieldsvar firstname = document.getElementById("firstname")var lastname = document.getElementById("lastname")var jsonBtn = document.getElementById("jsonbtn")var jsonText = document.getElementById("jsontext")//add click event listener, to get data when data is enteredjsonBtn.addEventListener("click", function(){//store data in JavaScript objectvar data = {"firstName":firstname.value,"lastName":lastname.value}//convert JavaScript object to JSONjsonText.innerHTML = JSON.stringify(data)})
Explanation
Lines 2–5: We get the references to the input fields and buttons and assign them to variables.
Line 9: We add a
clickevent listener to get the input data from the user.Line 11: We store the input data in the JavaScript object,
data.Line 16: We convert the input data stored in the JavaScript object,
data, to JSON using theJSON.stringify()method by passingdataas a parameter. Next, we display the returned JSON on the HTML page.
Free Resources