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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
WP_Query Class in WordPressWordPressWordPress: How to find all posts with a specific custom field value?WordPressHow to create rotating texts using JavaScript and CSS?CSSWhat does JSX do in React?ReactHow to add a ribbon on top of a container using CSS?CSSFile System Integrity: How to Keep an Eye on Your Files and Folder Change?Miscellaneous