Skip to content
Advertisement

How can I add or subtract numbers to a counter with a button using javascript?

Hello I’m new to javascript and code in general, and I’m stuck. I would like that when I click on a button the counter increases by x numbers. For example a button +100 or -100 and with each click it increments the counter.

I tried that but the button only works once.

            <script>
                price = 100
                money = document.getElementById('money').value
                function buyButtonClick(){
                    document.getElementById('money').value = money-price;
                }
            </script>
<input type="text" id="money" value="200"></input>
<button onclick ="buyButtonClick() id="buy-button">buy</button>

Advertisement

Answer

You need to get a current value each time from #money so move that into your function. You also need to ensure it’s a number (since all values taken from elements are strings), so add the + in front. Finally, you probably don’t want it to go below zero, so you can use Math.max() to make sure it doesn’t go into the red.

let price = 100
function buyButtonClick() {
  money = +document.getElementById('money').value
  document.getElementById('money').value = Math.max(0, money - price);
}
<input type="text" id="money" value="200"></input>
<button onclick="buyButtonClick()" id="buy-button">buy</button>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement