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 fields
var 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 entered
jsonBtn.addEventListener("click", function(){
//store data in JavaScript object
var data = {
"firstName":firstname.value,
"lastName":lastname.value
}
//convert JavaScript object to JSON
jsonText.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 click event 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 the JSON.stringify() method by passing data as a parameter. Next, we display the returned JSON on the HTML page.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved