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.
In this example, we'll get the input from HTML, store the data in a JavaScript object, and convert it to JSON.
//get references for text input and button fields firstname = document.getElementById("firstname") lastname = document.getElementById("lastname") jsonBtn = document.getElementById("jsonbtn") jsonText = document.getElementById("jsontext") //add click event listener, to get data when data is entered jsonBtn.addEventListener("click", function(){ //store data in JavaScript object data = { "firstName":firstname.value, "lastName":lastname.value } //convert JavaScript object to JSON jsonText.innerText = JSON.stringify(data) })
click
event listener to get the input data from the user.data
.data
, to JSON using the JSON.stringify()
method by passing data
as a parameter. Next, we display the returned JSON on the HTML page.RELATED TAGS
CONTRIBUTOR
View all Courses