Skip to content Skip to sidebar Skip to footer

How To Save A Number Into LocalStorage That Increments Each Time The User Enters A New Number?

I am having trouble wrapping my head around this problem. I made a small Javascript program in which the user enters a number and it displays a percentage. It also displays the tot

Solution 1:

You assume at multiple places the variable to be a Number while actually it is a string.

Use parseInt to use value as a number.

Here:

minutes = parseInt(document.getElementById('userInput').value) || 0;

And Here:

localStorage["time"] = (parseInt(localStorage["time"]) || 0) + minutes;
document.getElementById('storage').innerHTML = localStorage["time"] + " minutes";

Here is an updated fiddle with the changes.

Note that the || part after parseInt is for cases when the parse returns a NaN


Post a Comment for "How To Save A Number Into LocalStorage That Increments Each Time The User Enters A New Number?"