Function to add a variable when clicking on JavaScript

4

I'm trying to make a function that every time I click a button, add a value to a variable, and it shows on the screen but it does not work.

Any ideas on how to fix it?

<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
var a = 0;
function myFunction() {
    a = a + 1;
}
document.getElementById("demo").innerHTML = a;
</script>
    
asked by francesc 08.10.2016 в 16:26
source

4 answers

6

You have to put the output inside the function and better use textContent .

var a = 0;
function myFunction() {
  a = a + 1;
  document.getElementById("demo").textContent = a;
}
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
    
answered by 08.10.2016 / 16:35
source
0

Variables that are created within a function do not work for the rest of the code outside of the function.

<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
var a = 0;
function myFunction() {
    a = a + 1;
    document.getElementById("demo").innerHTML = a;
}
</script>
    
answered by 08.10.2016 в 18:12
0

This is a perfect example to implement a lock pattern. The code is elegantly encapsulated without global initializations.

 var contador = (function() {
  var c = 0;
  return function() {
     return ++c;
  }
})();
var eventoClick = function() {
   document.getElementById("demo").innerHTML = contador();
}
<button onclick="eventoClick()">Click me</button>
<p id="demo"></p>
    
answered by 30.10.2018 в 15:38
-1

You can try something like this:

<button onclick="myFunction()">Click me</button>
<p id="demo">0</p>
<script>
function myFunction() {
  var a = parseInt(document.getElementById("demo"));
  a = a + 1;
  document.getElementById("demo").innerHTML = a;
    }

</script>

The problem is that you have not started the value to 0, and that's why when you try to do the sum, you do not receive any results

    
answered by 08.10.2016 в 16:39