Adin Sijamija
Adin Sijamija

Reputation: 734

localStorage only saves first member of array


Every time I want to get the array from localStorage it only gets me the last value.I think it handles the array as a object. How do I fix this?

function saveData() {


    if ($("#forma").valid() == true) {

        var Name = document.getElementById("username").value;
        var Year = document.getElementById("godinaupisa").value;
        var Index1 = document.getElementById("brindeksa").value;
        console.log(Name);
        var EMial = document.getElementById("email").value;
        var OBJ = { NAME: "JOHN DOE", YEAR: "18", INDEX1: "1", EMAIL: "@" };


        OBJ.NAME = Ime1;
        OBJ.YEAR = Year;
        OBJ.INDEX1 = Index1;
        OBJ.EMAIL = EMial;

        var arrayOBJ = [];
        arrayOBJ.push(OBJ);

        localStorage.setItem("ARRAY", JSON.stringify(arrayOBJ));
        alert("saved");

        $("#forma").resetForm;

    };
}

Upvotes: 0

Views: 504

Answers (2)

Khauri
Khauri

Reputation: 3863

Because you create the arrayOBJ array each time you try to save, you're only ever going to have one item inside of it. And when you save it to localstorage you're just writing over anything that was already there. Instead try defining arrayOBJ outside your save function as a global variable. Alternatively you can use localStorage.getItem and JSON.parse to get the current array that's in localStorage before pushing to it.

Upvotes: 1

Adam LeBlanc
Adam LeBlanc

Reputation: 962

So, you're calling setItem which will just set it to whatever you pass it. I think what you want to go is read the current value, append to that and set the new value to be that.

var data = localStorage.getItem("ARRAY");
data = JSON.parse(data);
data.push(OBJ);
localStorage.setItem("ARRAY", data);

Upvotes: 2

Related Questions