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.
data form functions JSON local storage objects