Reputation: 3
I'm completely new to the JS (haven't done anything in it before) and as a part of my school assignment, which is a Pyhton server using HTML templates, I have to make a button in a .tpl file that will increase a variable by 1 every time it will be clicked:
<script>
var counter=0;
function add1() {
counter +=1;
document.getElementById("pplGoing").innerHTML = counter;
}
</script>
And the HTML part:
<button onclick="add1()">I'm going</button>
<p> Number of people attending: <span id="pplGoing"></span></p>
The button is working without any problems, as every time you click it, the number will increase by 1 (I know it's very simple, but as I said before, I have no experience in JS). But the problem is that every time you go back or refresh the page or restart the server, the pplGoing variable is being reset back to 0. Is it possible to somehow overwrite that variable, so the number will remain? The variable is stored in a .json file, which serves as a database. Thanks :)
Upvotes: 0
Views: 247
Reputation: 86
You can use localStorage
for saving the variable. Or cookies
for save and sync between client and server.
For example
<script>
var counter = 0;
document.addEventListener("DOMContentLoaded", function() {
counter = localStorage.getItem("counter"); // get value from storage
document.getElementById("pplGoing").innerHTML = counter; // restore value
});
function add1() {
counter++;
localStorage.setItem("counter", counter);
document.getElementById("pplGoing").innerHTML = counter;
}
</script>
Check the documentation.
Upvotes: 2