Yogesh Chauhan's Blog

How to create and store JSON objects in localStorage using JavaScript?

in JavaScript on July 14, 2021

This is how you can store data in browser using Storage interface of Web Storage API.

setItem


localStorage.setItem('name', 'Yogesh');

getItem

This is how you can get that stored data:


localStorage.getItem('name');

You can save that in a variable or directly print it, up to you.

If you have a form on your website and you want to save data of user inputs then you can use this function to retrieve the values and save those values in localStorage.

setItem with JSON object

We need to use JSON.stringify() function to save the JSON object.


function saveData() {
  let name = document.getElementById("name").value;
  let email = document.getElementById("email").value;
  let address = document.getElementById("address").value;

  let data = {
    name: name,
    email: email,
    address: address,
  };

  localStorage.setItem("data", JSON.stringify(data));
}

getItem with JSON object

We need to use JSON.parse() function to get and parse the JSON object.


function fillForm() {
  let localData = JSON.parse(localStorage.getItem("data"));

  document.getElementById("name").value = localData.name;
  document.getElementById("email").value = localData.email;
  document.getElementById("address").value = localData.address;
}

You can add more conditions for e.g. check if the JSON object is empty or not.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to change style of nth-child using jQuery?jQueryCSS Overflow Property with ExamplesCSSHow to Install PHP Laravel on MacOS Catalina?PHPHow to create a circle that follows a cursor using JavaScript and CSS?CSSHow to add a Pie Chart in Angular App?AngularURL paths in DrupalDrupal