Function add number

1

Can someone tell me how to do a function assigned to a button that takes a number inside the DOM, adds X and replaces the old number with the new one?

I've tried this.

var boton = document.getElementById("boton"); //variable de boton para incrementar valor
var numero = document.getElementById("numero").value;  //variable del numero en el DOM

boton.addEventListener("click", boton);        

function lvl1cash() {                             
  var result = numero++;                               //variable con el resultado
  document.getElementById("numero").innerHTML = result; //Muestra resultado de la funcion en DOM
}
<h3 id="numero">1</h3>
<button id="boton" value="Boton" onclick="boton">SUMAR</button>
    
asked by Alejandro 14.11.2017 в 21:44
source

2 answers

2

You must bear in mind that to capture the value of a form element, .value is used, but when the element is a different element (as in this case it is a <h3> ) .innerHTML must be used to capture its content, after doing that in addEventListener you must indicate the function that will be executed when you click on the button, like this:

var boton = document.getElementById("boton"); //variable de boton para incrementar valor

var numero = document.getElementById("numero").innerHTML; //variable del numero en el DOM

boton.addEventListener("click", lvl1cash);        

function lvl1cash() {
  var result = ++numero;                               //variable con el resultado
  document.getElementById("numero").innerHTML = result; //Muestra resultado de la funcion en DOM
}
<h3 id="numero">1</h3>
<button id="boton" value="Boton" onclick="boton">SUMAR</button>
    
answered by 14.11.2017 / 21:52
source
2

You can also do it with jQuery, being much friendlier:

// variable de boton para incrementar valor
var $boton = $("#boton");
// variable del numero en el DOM
var $numero = $("#numero").text();


$boton.on("click", lvl1cash);

function lvl1cash() {
  // Muestra resultado de la funcion en DOM
  $("#numero").text(++$numero);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3 id="numero">1</h3>
<button id="boton" value="Boton">SUMAR</button>
    
answered by 17.11.2017 в 21:51