0

i'm trying to insert values from input field into an array then store it in localstorage, but the problem is every time i insert a new value it replaces the old value, rather i want it to be added to the existing values . bear with me if it's a silly question, i am a newbie :)

<html>
<body>

  <form>
    <input id="textInput" type=text>
    <input type=button onclick="myFunction()" value="Add Number"/>
  </form>
  <div id="output"><div>

  <script>
    function myFunction() {
      var sports = ["soccer", "baseball"];
      var newSport = document.getElementById('textInput').value;
      sports.push(newSport)
      window.localStorage.setItem("sportskey", sports);
      document.getElementById('output').innerHTML = window.localStorage.getItem('sportskey');
    }
  </script>

</body>
</html>
2
  • 3
    Pretty sure you can't store an array in localStorage. I think you need to JSON.stringify() and JSON.parse(). Commented May 16, 2014 at 13:53
  • 1
    Also, every time myFunction() is ran, you re-create the array sports. You only need to do that if it doesn't already exist in localStorage. Commented May 16, 2014 at 13:54

4 Answers 4

1

Your sports variable is local to the function, so it gets reinitialized every time the function runs. To fix it, move the declaration outside of the function.

Also, as @RocketHazmat pointed out, you can only store a string. Therefore, your new code snippet should look like:

var sports = ["soccer", "baseball"]; //global scope
function myFunction() {
  var newSport = document.getElementById('textInput').value;
  sports.push(newSport)
  window.localStorage.setItem("sportskey", JSON.stringify(sports)); // store as a string
  document.getElementById('output').innerHTML = window.localStorage.getItem('sportskey');
}
Sign up to request clarification or add additional context in comments.

Comments

1

the problem is in the scope of the variables. Your sports array must be declared outside of the myFunction() function

<script>
    var sports = ["soccer", "baseball"];
     function myFunction() {

      var newSport = document.getElementById('textInput').value;
      sports.push(newSport );
      var myString= JSON.stringify(sports);

      window.localStorage.setItem("sportskey", myString);
      document.getElementById('output').innerHTML = window.localStorage.getItem('sportskey');
    }
  </script>

Comments

0

Aaargh... im too late with my answer ;)

Yes you re create the array everytime the method is called and you should call JSON.stringify(Array) on storing the item and JSON.parse(string_from_localStore) when loading the item from localStore.

But you should wrap the stringify in an try and catch block, because it can be some reasons when the json string is not well formed that your stringify method crashes the function and it stops working.

var myFunc = function() {
      //load it at first from localstorage
      var sports = ["soccer", "baseball"];
      var localSports = [];
      try {
          localSports = JSON.parse(window.localStorage.getItem('sportskey'));
          if( localSports == null)
              localSports = sports;
      } catch(ex) {
          console.log("something wrong");
          localSports = sports; //fallback
      }
      var newSport = document.getElementById('textInput').value;
      localSports.push(newSport); //this is an array
      //insert the array with JSON.stringify so you can take it later out and rework with it          
      window.localStorage.setItem("sportskey", JSON.stringify(localSports));
      output.innerHTML = window.localStorage.getItem('sportskey');
};

Here is the link to the jsfiddle:

http://jsfiddle.net/bgh7f/

1 Comment

is there any way to remove a single particular item from the above example?
0

You are re-creating the sports array every time myFunction() is called. Each time you add a new one, you are starting from scratch, adding a 3rd element, and ignoring the others you already added.

Only create the array if it doesn't exist in localStorage.

P.S. You can't store arrays in local storage, only strings. You'll need to convert to/from JSON to make this work.

function myFunction() {
  var sports = JSON.parse(window.localStorage.getItem('sportskey')) || ["soccer", "baseball"];
  var newSport = document.getElementById('textInput').value;

  sports.push(newSport)

  var json = JSON.stringify(sports);
  window.localStorage.setItem("sportskey", json);
  document.getElementById('output').innerHTML = json;
}

DEMO: http://jsfiddle.net/EhH8C/

Comments

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.