How to code like simple shopping bag?

i am trying to code two button here , base number is 0, the number can be +/- when i click which one number. Now my problem is number only two answer:1,-1.

i want,
click + btn 3 times, the number should be 0 to 3 and
click - btn 2 times, the number should be 1.

i think my code is not clear and very very wrong.

<!DOCTYPE html>
<html>

<head>
    <title>ABCDEFG</title>
</head>

<body>
    <input id="btnPlus" type="button" value="+" onclick="numberPlus()">
    <input id="btnMinus=" type="button" value="-" onclick="numberMinus()">
    <p id="number">0</p>
    <script>
        function numberPlus() {
            var y;
            var x;
            y = 0;
            x = ++y; 
            document.getElementById("number").innerHTML= x;  
        }
        function numberMinus() {
            var y;
            var x;
            y = 0;
            x = --y; 
            document.getElementById("number").innerHTML= x;  
        }
        
    </script>
</body>

</html>

Hey there!
The variables are local to your function. That means that they don’t know about each other values.
What you need is a shared variable. Either defined outside the function or passed to the function.
You don’t even need two variables for this example, you are only decreasing/increasing one number.
If you place the variable x outside the two functions, both functions can access the variable. This means, all variables and functions have their own execution scope.

I prepared an example that you can see working:

Happy coding!

Cheers,
Martin

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.