1

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.

1

3 Answers 3

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

Comments

0

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();
}

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.