Question

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 total of the numbers entered. I am trying to display that total each time the user views the page. I want to use localStorage to save the number and display it on the screen every time a user visits the page.

http://jsfiddle.net/uyr7Z/

Here is the jsfiddle demo. The problem is that I cannot figure out how to increment a saved number. I want minutes to be added each time the calculate button is clicked.

Here is my code so far:

var decent = 1200;
var master = 600000;
var minutes;
var decentOriginal;
var masterOriginal;
var totalDecent=0;
var totalMaster=0;
var decentLeft= 1200;
var masterLeft= 600000;
var totalMin = 0;

function compute() {
    minutes = document.getElementById('userInput').value;
    decentOriginal = minutes/decent * 100;
    masterOriginal = minutes/master * 100;
    updatePercent();
    localStorage.time = localStorage.num + minutes;
    document.getElementById('storage').innerHTML = localStorage.time + " minutes";
}

function updatePercent() {
var decentPercent = document.getElementById('decent-percent');
var masterPercent = document.getElementById('master-percent');
var decentCompute = Math.round(decentOriginal*100)/100;
var masterCompute = Math.round(masterOriginal*100)/100;
decentLeft = decentLeft - minutes;
masterLeft = masterLeft - minutes;  
    totalDecent = totalDecent + decentCompute;
    totalMaster = totalMaster + masterCompute;
    totalMin = Math.round(totalMin + parseInt(minutes)/60);
    if(decentLeft<=0) {
        totalDecent = 100;
        decentLeft = 0;
        decentCompute = 0;  
    } 
    if(masterLeft<=0) {
        totalMaster = 100;
        masterLeft = 0;
        masterCompute = 0;
    }
    if(totalMin>=600000) {
        totalMin=600000;
    }


    decentPercent.innerHTML = totalDecent.toFixed(1) + "%" + " " + decentLeft + " minute(s) to go.";
    masterPercent.innerHTML = totalMaster.toFixed(2) + "%"  " " + masterLeft + " minute(s) to go.";
    document.getElementById('total-min').innerHTML = totalMin+" hours spent.";
}
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top