Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

json
html
communitycreator

How to save user input to JSON object in HTML

Gutha Vamsi Krishna

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
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)
})

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.

RELATED TAGS

json
html
communitycreator
RELATED COURSES

View all Courses

Keep Exploring