Reset button still holding value

Hi Guys,

I am writing a very basic program to increment, decrement and clear an input field.

Increment and decrement buttons are working fine, but my reset button seems to still hold the value; the visible value will reset, but once I increment/decrement the value from fresh, it still holds the previous value.

E.G.

If I increment to 4, then clear, the input field will reset to 0/blank. However, if I increment again, it just goes to 5, instead of 1 - any help would be greatly appreciated!

Code below:

JS:

let i = 0;
let valueInput = document.getElementById('valueText');
const button = document.getElementById('reset');


function incrementButton() {
   document.getElementById('valueText').value = ++i;
}

function decrementButton() {
   document.getElementById('valueText').value = --i;
}

function resetButton() {
   let alertBox = confirm("Are you sure you want to Reset?\nAll of your progress will be deleted.");

   if (alertBox == true) {
     valueInput.value = 0;
     valueInput = 0;
   } else {
      return false;
   }
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="stylesheet.css" rel="stylesheet">
    <title>JavaScript Counter</title>
</head>
<body>
    <div class="title">
        <h1>Counter</h1>
        <p>Please use the buttons below in order to achieve the desired number</p>
    </div>
        <div class="number">
            <input id="valueText" type="number" value="0"></input>
        </div>
    <fieldset id="button">
        <button type="button" class="increase" onclick="incrementButton()">Increase</button>
        <button type="button" class="decrease" onclick="decrementButton()">Decrease</button>
        <button type="button" id="reset" onclick="resetButton()">Reset</button>
    </fieldset>    
    <script src="script.js"></script>
</body>
</html> ```

Let’s pretend that i is currently 3 because you’ve incremented 3 times Then:

This code will:
1- confirm if the user wants to reset and if yes
2- update the value property of the valueInput element (which is currently set to an input element)
3- make the valueInput element variable equal to 0. (which has no effect on the what the user sees, as valueInput is just an internal variable)

Later on:

When the increment is called, you will retrieve the valueText element and its value and set it to whatever the i+1 is. Since we agreed that i was 3 before, then the new value will be 4.

No matter how many times you call reset, i doesn’t change because reset doesn’t change it.

1 Like

Hello again - thank you so much!

I completely forgot about the global application of code. I honestly forgot that I had used i = 0 at all in the global declaration as i was so focused on the function itself!

Massively helpful once again - thank you :slight_smile:

1 Like