Nazariy Nazariy - 2 months ago 12
HTML Question

Localstorage can't generate data Javascript

I want to generate new

div
element with some information from
input
, but it is not working correctly. I have a big problem with saving and receiving data from
localstorage
. I spent two days researching the issue. Would you be so kind to tell me where are the problems?

Fiddle: https://jsfiddle.net/v5r653nd/1/

var nameaaaa = document.getElementById("nameOfbook");
var author = document.getElementById("nameOfauthor");
var year = document.getElementById("year");

function makeJob() {
testObjects.push({
name: nameaaaa.value,
author: author.value,
year: year.value
})

localStorage.setItem('testObjects', JSON.stringify(testObjects));

Answer Source

If I understood correctly the problem, you are overwritting the localstorage since at start of the script you declare that testObject is an empty array and later you work over it and replace your localstorage with that values.

So you should retrieve the localstorage value first and store it in that variable:

var testObjects = localStorage.getItem("testObjects") ? JSON.parse(localStorage.getItem("testObjects")) : [];

JSFiddler Demo