Search code examples
javascripthtmlbuttononclickincrement

Button Incrementing Counter, but Counter Then Resets


I am trying to make a simple counter with increment and reset buttons. Whenever I click on increment, I can see that the counter goes from 0 to 1, as it should (if I console.log something, I can see it on the console on Chrome).

The problem is that, as soon as it increments, it resets back to 0, as if the page refreshes (the log in the console also clears, which is why I think that the page refreshes, I am not sure that it actually does).

Here is my code:

// Functions
const setCounter = (n) => document.getElementById("counter").innerHTML = n;
const resetCounter = () => setCounter(0);
const getCounterValue = () => parseInt(document.getElementById("counter").innerHTML);
const incrementCounter = () => setCounter(getCounterValue() + 1);

// Button Variables
var incrementButton = document.getElementById("increment-btn");
var resetButton = document.getElementById("reset-btn");

// Button Functions
incrementButton.onclick = () => incrementCounter();
resetButton.onclick = () => resetCounter();
<span id="counter">0</span>
<form class="counter-btns">
    <button class="btn" id="increment-btn" type="button">Increment</button>
    <button class="btn" id="reset-btn" type="button">Reset</button>
</form>

Similarly, if I hardcode the value of the counter to start at 3, clicking on the reset button sets the value to 0, but it instantly goes back to 3 (clicking on the increment button sets the value to 4, but it instantly goes back to 3).

Note: I am using VSCode. I have this issue both when i open the index.html with Chrome, or when I open it with Live Server on VSCode


Solution

  • try changing:

    <button class="btn" id="increment-btn">Increment</button>
    <button class="btn" id="reset-btn" type="button">Reset</button>
    

    to:

    <button type="button" class="btn" id="increment-btn">Increment</button>
    <button type="button" class="btn" id="reset-btn" type="button">Reset</button>
    

    but prefer to desactivate form action, because any return key on a form perform a form submit.

    // Functions
    const counterForm = document.forms['counter-btns']
      
    counterForm.onsubmit = e =>
      {
      e.preventDefault()  // desactivate form submit  (no page relaod)
      counterForm.counter.textContent = 1 + +counterForm.counter.textContent
      }
    counterForm.onreset = e =>
      {
      counterForm.counter.textContent = 0
      }
    <form name="counter-btns">
      <output name="counter" > 0 </output>
      <button>Increment</button>
      <button type="reset">Reset</button>
    </form>

    nb: + (sign) as first character act like a parseInt()