I'm trying to use local storage to store a number so that it stays even if i refresh or revisit the page, but whenever i refresh the return value is 0.
I know that it's probably a really easy fix that I can't figure out but i would very much appreciate an answer to this beginners (probably) easy question.
In case you were wondering this is for a star rating system.
HTML:
<p id="r1"></p>
jQuery:
$(document).ready(function(){
var x1;
x1 = +localStorage.getItem("x1");
$("#r1").html("Your rating: " + x1);
$("#rating1 span").click(function() {
x1 = 5 - $(this).index();
$("#r1").html("Your rating: " + x1);
});
localStorage.setItem("x1", x1);
});
First problem is that you're not providing the name of the local storage item when you retrieve it with getItem
, that should be localStorage.getItem("x1")
.
The second problem is that you're calling setItem()
when the page is loaded, not when the user clicks on the rating, so it's not using the rating that the user selects.
$(document).ready(function(){
var x1;
x1 = +localStorage.getItem("x1");
$("#r1").html("Your rating: " + x1);
$("#rating1 span").click(function() {
var x1 = 5 - $(this).index();
$("#r1").html("Your rating: " + x1);
localStorage.setItem("x1", x1);
});
});