ekbayrak2 ekbayrak2 - 19 days ago 5
Javascript Question

javascript array in localstorage

I have this piece of code that adds values to an array with an input box. I would like to save that array in

localStorage
and display the contents of the array on another page.

<button type="button" id="submit">Submit</button>
<button type="button" id="display">Display</button>


window.onload = function() {
var inputArray = [];
var input = document.getElementById('inputbox');
var screen = document.getElementById('screen');

document.getElementById('submit').onclick = function () {
inputArray.push(input.value);
screen.innerHTML = input.value;
};

document.getElementById('display').onclick = function () {
screen.innerHTML = inputArray
};
}

Answer

You are not persisting data in localStorage. As localStorage persist only string data, You can stringify while storing and parse while reading.

 window.onload = function() {
     var inputArray = [];

     //Check if data is persisted in localStorge then load in the array
     var str = localStorage.getItem('nyArray')
     if (str) {
         inputArray = JSON.parse(str);
     }

     var input = document.getElementById('inputbox');
     var screen = document.getElementById('screen');

     document.getElementById('submit').onclick = function() {
         inputArray.push(input.value);
         screen.innerHTML = input.value;

         //Store stringifyed string
         localStorage.setItem('nyArray', JSON.stringify(inputArray))
     };

     document.getElementById('display').onclick = function() {
         screen.innerHTML = inputArray
     };
 }
Comments