I'm learning JavaScript for the first time and currently working on a quiz, I'm trying to calculate the number of attempts each student has had at doing the quiz (they enter in their student ID in the form) Each student has a maximum of 3 attempts and I'm trying to store this information in "localStorage.attempts"
In the function below I have an if statement that checks whether the variable "attempts" (which is either assigned 0 or the value of "localStorage.attempts") is less than or equal to 3 and if the ID just entered matches the ID saved in storage. If these conditions are met, "attempts" is incremented by 1. This works fine with an ID never used before, "attempts" goes from 0 to 1. When the same ID is entered again, I expected 1 to be added to 1 therefore equaling 2, but no, remarkably the integers are appended instead like so: 11. The code thinks the user has had 11 attempts when they're only on their second. I've added alerts everywhere to track what's going on. I can't tell if this is some sort of bug or if I just need sleep.
function numberOfAttempts()
var errMsg = "";
var attempts;
alert("1:" + attempts + localStorage.attempts);
if (localStorage.attempts == undefined) {
attempts = 0;
alert("2: localstorage is undefined" + attempts + localStorage.attempts);
}
else {
attempts = localStorage.attempts;
alert("attempts is assigned to localStorage.attempts" + " " + attempts + localStorage.attempts);
}
alert("3: " + attempts + " " + localStorage.studentID + " " + document.getElementById("studentID").value);
if (attempts <= 3 && document.getElementById("studentID").value == localStorage.studentID) {
attempts = attempts + 1;
alert("4: incrementing attempts" + " " + attempts + " " + localStorage.attempts);
}
alert("5: " + attempts + localStorage.attempts);
if (document.getElementById("studentID").value != localStorage.studentID) {
attempts = 0;
alert("6: reseting attempts" + attempts + localStorage.attempts);
}
localStorage.attempts = attempts;
}