Hsan Hsan - 1 month ago 7
Javascript Question

Display localstorage in input on load

I have a small web calculator which calculates time. My mobile browser gets rid of all data when I've minimised/closed the mobile broswer for a few minutes or on a page refresh so I've made a button which can reload all previous data and displays as text.

I want to get rid of the "Get old data" button and just have the page reload with all the values displayed in the input box as they were before the page refresh.

I've been thinking an onload event in the input box would work but as i understand this is not possible.

HTML

<body onload="getreload()">
<p>Please enter minutes</p>
<input type="text" id="etime">
<br>
<p>Please enter time in 24 hour format (eg. 15:00)</p>
<input type="text" id="stime">
<br>

<br>
<button onclick="myFunction()">Calculate</button>
<p id="finishtime">
<br>
<br>
<button onclick="getreload()">Get old data</button>
<p id="finishtime2">

<p id="mintime2">
</body>


Javascript

function myFunction() {



function converToMinutes(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}

function parseTime(s) {
var seconds = parseInt(s) % 60;
return Math.floor(parseInt(s) / 60) + ":" + ((seconds < 10)?"0"+seconds:seconds);
}


var endTime = document.getElementById("etime").value;
var startTime = converToMinutes(document.getElementById("stime").value);
var converted = parseTime(startTime - endTime);


document.getElementById('finishtime').innerHTML = "You will finish your break at " + converted;

if (typeof(Storage) !== "undefined") {
localStorage.setItem("convertedTime", converted);
localStorage.setItem("endTimeReload", endTime);
} else {
// Sorry! No Web Storage support
}

}


function getreload() {
var convertedTime = localStorage.getItem("convertedTime");
document.getElementById('finishtime2').innerHTML = "End of break time: " + convertedTime;


var endTimeReload = localStorage.getItem("endTimeReload");
document.getElementById('mintime2').innerHTML = "Minutes till next client: " + endTimeReload;
}

Answer

You are mostly there, but you are not restoring correctly and not saving the startTime. Here is a fiddle with everything you need: https://jsfiddle.net/22ej8scw/

Restore like this. (I also changed how it is saved)

function getreload()    {
    var startTime = localStorage.getItem("startTime");
    document.getElementById("stime").value = startTime;

    var endTimeReload = localStorage.getItem("endTimeReload");
    document.getElementById("etime").value = endTimeReload;

    if (startTime && endTimeReload)
        myFunction();
}