I would like to make a simple counter script, which assign a number value for a text value (e.g. good - 1, moderate - 2, excelent - 3), after i would like to store that value in the session storage and after a page reload, i would like to continue the counting from the previous result value.
I have the counter script, and the HTML but I couldn't restore the previous value and continue the counting. Here is the script:
function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0; document.getElementById('qty').value = new_qty;
document.getElementById("result").value = sessionStorage.getItem("qty");
document.getElementById("result").innerHTML = sessionStorage.getItem("qty");
}
document.getElementById('qty').value = new_qty;
return new_qty;
}
I use the following html:
<table id="main">
<tr>
<td><button id="up" onclick="modify_qty(1)">Poor</button> </td>
<td><button id="up" onclick="modify_qty(2)">Moderate</button></td>
<td><button id="up" onclick="modify_qty(3)">Good</button></td>
<td><button value="Refresh Page" onClick=" sessionStorage.qty = qty.value; window.location.reload();">Reload</button></td>
<td><button value="Clear" onClick="sessionStorage.clear (result);window.location.reload();">Clear</button></td>
</tr>
</table>
</div><br><br><br><br><br><br><br>
<div class="box">
<input id="qty" type="text" value="0" />
<input id="result" value="0"/>
So basically I would like to Select the Moderate (2) button it will give 2 "points" to the session storage, and after I refresh the page, the counter will show "2" and I would hit the Good (3) button and after the second refresh the counter should show "5". Its a little bit complicated but I got stuck.
Any idea?
For some reason, this has a script error when posting it via Stack Overflow's Code Snippet so I used JSFiddle.
https://jsfiddle.net/kqexbhmo/
<div class="container">
<h3>Example</h3>
<div data-score="1">good</div>
<div data-score="2">moderate</div>
<div data-score="3">excellent</div>
<div id="reset">reset</div>
<div id="score"></div>
</div>
var votes = document.querySelectorAll('[data-score]');
for (var ix = 0; ix < votes.length; ix++) {
votes.item(ix).addEventListener('click', function() {
localStorage.setItem('score', getScore() + parseInt(this.dataset.score, 10));
showScore();
});
}
document.getElementById('reset').addEventListener('click', function() {
localStorage.removeItem('score');
showScore();
});
function getScore() {
return parseInt(localStorage.getItem('score') || 0, 10);
}
function showScore() {
document.getElementById('score').innerText = getScore();
}
showScore();