Analysis
If we look at the code, we can find the following line:
calc.addEventListener("click", maths);
This assigns a listener to the calc
element, but What does this mean?
When you click on the calc
element, it will execute a function.
Where is the problem?
The problem comes to occur in the fact that we are not saving the result returned from that function anywhere.
We have this line:
var um = maths();
document.write(um);
Simply run the maths()
function, and voila, the valor
returned from the function maths()
is assigned to the variable um
and the value is printed ... It does not pass nothing more.
Why does not the button work for us?
We have only assigned the listener , but we have not assigned the result of the function to any element.
How could we solve it?
One solution could be this:
/* Asignamos el listener */
var calc = document.getElementById('gosqrt');
calc.addEventListener("click", botonPresionado);
/* Creamos una variable que contendra el resultado */
var resultado;
/**
* Funcion maths()
* Calcula la raiz cuadrada
*/
function calcularRaiz() {
var b = document.getElementById("sqrt").value;
return Math.sqrt(b);
}
/**
* Funcion botonPresionado()
* Funcion a ejecutar cuando se presione el boton
*/
function botonPresionado() {
resultado = calcularRaiz();
alert(resultado);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="sqrt" placeholder="Square root"/>
<input type="button" id="gosqrt" value="Calcular"/>
</body>
</html>
What have we done here?
We create a global variable , called resultado
and in it we save the result of the function calcularRaiz()
(previous maths ()) , and execute a alert()
, to show the result of the operation.