0

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 :)

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.