Cha0stra
Cha0stra

Reputation: 11

Using Local Storage on For-Loop

I'm new to JavaScript and i'm trying to create a code where for each checkbox item checked, a point is added to the id=result THEN the result is saved in local storage. Problem is, it won't save the generated result.

<script>
 function score() {
 var score = document.forms[0];
 var i;
 var points=0;
 if(typeof(Storage) !== "undefined") {
  for (i = 0; i < score.length; i++) {
    if (score[i].checked) {
        points++;
    }
 }
 document.getElementById("result").innerHTML = "Current Score: " + points;
 localStorage.setItem= ("points", JSON.stringify(points));
 document.getElementById("result").innerHTML = localStorage.getItem('points');

}
else {
    document.getElementById("result").innerHTML = "Sorry, your browser does 
not support web storage...";
     }
}
</script>

It shows the result but it does not save it. Any help would be appreciated :)

Edit Changed localStorage.setItem= ("points", JSON.stringify(points)); to localStorage.setItem("points", JSON.stringify(points)); As suggested by Moon But now it won't show the results.

Upvotes: 0

Views: 421

Answers (1)

moon
moon

Reputation: 670

Fix

localStorage.setItem= ("points", JSON.stringify(points));

to

localStorage.setItem("points", JSON.stringify(points));


And, as a different way, you can also just check like this to know if localStorage exsits.
Just to let you know :)

if(!window.localStorage){
    ... do something ....
}

Upvotes: 3

Related Questions