[Solved] How to make a button in HTML which decrement a variable?


Your function only changes the value of the Stock variable.

It doesn’t change the value of document.getElementById("myText").innerHTML which only gets changed when you call myFunction (something you never do).


You need to:

  • Actually call myFunction when the document loads
  • Call it again whenever you change the variable.
let stock = 10;

function myFunction() {
  document.getElementById("myText").innerHTML = stock;
}

function buttonFunction() {
  stock--;
  myFunction();
}

document.querySelector("button").addEventListener("click", buttonFunction);

addEventListener("load", myFunction);
<button>ClickMe</button>

<h1>"The value for Stock is: " <span id="myText"></span></h1>

Also note that by convention, variable names which start with a capital letter are reserved for classes and constructor functions in JS, so rename your variables.

0

solved How to make a button in HTML which decrement a variable?