javascript calculator without using eval ();

0
var memoria = document.getElementById('pantalla').value;
var memoria2 = document.getElementById('pantalla').value;
//almaceno en variable el valor del campo id="pantalla", en esta caso es un input tipo text.

Now I have to create a function that:

  • Delete field input type text with id="pantalla" , but keep the value of the variable memory.

  • I must rewrite another value in the field input type text with id="pantalla" and add it to the variable memory.

I have tried to do this but it does not work. Does anyone have any better idea of how I could do it?

function sumar(){
  document.getElementById('pantalla').value = ""; //Esto borra el campo.
   document.getElementById('pantalla').value = "memoria2";
   var suma = (memoria + memoria2)
   document.calcu.visor.value = suma;
}
    
asked by Alex 22.10.2016 в 19:56
source

2 answers

1

Test using IIFE

(function() {
  var pantalla = document.getElementById('pantalla'),
    valor = document.getElementById('valor'),
    sumar = document.getElementById('sumar'),
    borrar = document.getElementById('borrar'),
    memoria = 0;
  
  sumar.addEventListener('click', function() {
    var numero = parseFloat(valor.value, 10) || 0;
    
    memoria += numero;
    pantalla.value = memoria;
    valor.value = '';
  });
  borrar.addEventListener('click', function() {
    memoria = 0;
    pantalla.value = memoria;
  });
})();
Pantalla: <input type="text" id="pantalla" readonly /><br />
Valor: <input type="text" id="valor" /><br />
<input type="button" id="sumar" value="Sumar" /><br />
<input type="button" id="borrar" value="Borrar" />
    
answered by 24.10.2016 в 13:35
0

Add the variable within the function and another variable that controls the times the input was sent

var num = 0
function sumar(){
  if(num == 0){
    var memoria = document.getElementById('pantalla').value
    document.getElementById('pantalla').value = ""
    num++
  }
  else if(num == 1){
    var memoria2 = document.getElemtById('pantall').value
    document.getElementById('pantalla').value = ""
  }
  else{
    var suma = memoria + momoria2
    document.calcu.visor.value = suma
  }
}
    
answered by 22.10.2016 в 21:21