Reputation: 5
I have a section on my website that allows you to earn digital points and spend them on games and stuff, but it is hard to use. I am redoing it to make use of localStorage
, and make the whole system easier to use. I ran into a problem, though. I created a function to add points using javascript, and I created a button that will temporarily allow me to run it easily. When I click the button, it should add 10 points to the current total of 0 points, and end up with 10 points total, but instead it adds 0 and 10 as strings and comes up with 010 points. This is the function that is run by pressing the button:
function addPoints(number) {
var pointsExist = localStorage.getItem("points");
var newPointsTotal = pointsExist + arguments[0];
localStorage.setItem("points", newPointsTotal);
location.reload();
}
This is the function that checks the current number of points and displays it:
function check() {
var points = localStorage.getItem("points");
if (!points) {
var points = +0;
localStorage.setItem("points", points);
}
document.getElementById("points").innerHTML = "Hi, " + username + "! You have " + points + " points.";
}
In case you find it helpful, I have created a hidden directory on my website with the page in it, and you can click on this link to go there and try it out yourself if I did not explain it well.
Upvotes: 1
Views: 74
Reputation: 297
Your points are saved as strings in localStorage
. You should make a number.
function addPoints(number) {
var pointsExist = localStorage.getItem("points");
var newPointsTotal = Number(pointsExist) + arguments[0];
localStorage.setItem("points", newPointsTotal);
location.reload();
}
Upvotes: 1
Reputation: 44087
You need to parse the JSON in localStorage
to integers:
function addPoints(number) {
var pointsExist = parseInt(localStorage.getItem("points"));
var newPointsTotal = pointsExist + number;
localStorage.setItem("points", newPointsTotal);
location.reload();
}
Upvotes: 0
Reputation: 12152
In localStorage all the values are stringified, so pointsExist is given out as string. You have to change it to number before adding
function addPoints(number) {
var pointsExist = localStorage.getItem("points");
var newPointsTotal = parseInt(pointsExist) + arguments[0];
localStorage.setItem("points", newPointsTotal);
location.reload();
}
Upvotes: 0