Home > front end >  I am trying to decrease a number in a variable in javascript
I am trying to decrease a number in a variable in javascript

Time:11-20

I have been using the thing in HTML to wright in javascript and I am trying to do the math of a = a - 1 to try to decrease and print a number when you press a button.

this is my code

<body>
<button id="button" type="button">day passed</button>  
<p id="demo"></p>
<script>
    var a = 37;
    var submitButton = document.getElementById("button"); 
submitButton.addEventListener("click", function() {
    var a = a - 1;
    document.getElementById("demo").innerHTML = a;
     })</script>


</body>

how do I fix this or just do it in general

CodePudding user response:

<body>
<button id="button" type="button">day passed</button>  
<p id="demo"></p>
  <script>
    let a = 37;
    let submitButton = document.getElementById("button"); 
    submitButton.addEventListener("click", function() {
      a--;
      document.getElementById("demo").innerHTML = a;
    })
  </script>


</body>

this works fine.

try to work with let or const instead of var.

CodePudding user response:

Just change var a = a - 1 to a = a - 1 or a -= 1

var a = 37;
var submitButton = document.getElementById("button");
submitButton.addEventListener("click", function() {
  a -= 1;
  document.getElementById("demo").innerHTML = a;
})
<button id="button" type="button">day passed</button>  
<p id="demo"></p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related