1

I have been trying to code in javascript where I want input given to be displayed on screen. I want to store the data from input in LocalStorage. I tried to take the value and using localStorage.setItem and localStorage.getItem I stored in local storage too. But as I want to display all the records I have inserted every time submit button has been clicked, I want to store current and previous records too. I tried to push into an array but it had only current records and not previously stored values. I don't want jquery. I just want simple javascript code. thank you.

   eg-
    var data=[];
    function myFunction(data)
    { 
         var name= document.getElementById("nm").value;
         localStorage.name= name;
         for(var i=0;i<localStorage.length;i++)
         {
             var key = localStorage.key(i);
             var value = localStorage.getItem(key);
             data.push( value);
         }
     }
1
  • Please show how you currently store the data also. Would be simplest to store json representation of array and then parse the when getting it out of storage. A convenient little library script is Store.js Commented May 29, 2016 at 15:40

1 Answer 1

2

Yep, as mentioned in the comments it is best to just store the String representation of your array and store it as a value in localstorage. Web localstorage lets you store simple key value pairs which can be integers or strings (mostly strings) official docs

You could do something like this:

 var name= document.getElementById("nm").value;
 var data;
 if (localStorage.getItem("name") === null)
   //First value to be stored
   data = [];
 else
   //There is some value already in the array
   data = JSON.parse(localStorage.getItem("name"));

 //Push name to data array in any case
 data.push(name);
 //Update localStorage
 localStorage.setItem("name",JSON.stringify(data));

I hope this gets you started in the right direction.

Sign up to request clarification or add additional context in comments.

4 Comments

localStorage.setItem("name") = JSON.stringify(data) - this is wrong usage of localStorage.setItem(key, value) method
@RomanPerekhrest, thanks a ton for pointed it out! Noted and updated :)
Thank u for the ans, but its giving data.push is nt a function error. why? eventhough data is an array
@Sarah, sorry for the late reply. Try doing typeof(data) where you are getting the error. It should ideally be an array. We can force it during declaration so where I do var data;, try var data=[]; and see if it solves your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.