1
Hello,
I’m starting in JS and decided to make a calculator.
I created a function that should pull the data from the display that receives the data clicked on the calculator and is also an input, and another that pulls the data from this function when we click '=' and returns this value where I created the result field. The function I created, when I test in the terminal, works with the parameters "operator", value1, value2. But when it’s in the code retrieving the values from the display, it returns Undefined to me. You can clear this up for me?
Thank you!
The code is like this:
<section id="calculadora">
<div type="number" name="resultado" id="resultado"></div>
<input type="text" name="intro" id="intro">
<input type="button" class = "oper" value="1" onclick="numero(1)" >
<input type="button" class = "num" value="2" onclick="numero(2)">
<input type="button" class = "num" value="3" onclick="numero(3)">
<input type="button" class = "num" value="0" onclick="numero(0)">
<input type="button" value="CE" onclick="limpar()">
<input type="button" class = "num" value="4" onclick="numero(4)">
<input type="button" class = "num" value="5" onclick="numero(5)">
<input type="button" class = "num" value="6" onclick="numero(6)">
<input type="button" class = "oper" value="-" onclick="operacao(value)">
<input type="button" class = "oper" value="/" onclick="operacao(value)">
<input type="button" class = "num" value="7" onclick="numero(7)">
<input type="button" class = "num" value="8" onclick="numero(8)">
<input type="button" class = "num" value="9" onclick="numero(9)">
<input type="button" class = "oper" value="+" onclick="operacao(value)">
<input type="button" class = "num" value="x" onclick="operacao(value)">
<input id="verificar" type="button" value="=" onclick="calcular()">
</section>
<script>
var intro = document.getElementById("intro")
var resultado = document.getElementById("resultado")
function limpar(){
intro.value = ""
}
function numero(value){
intro.value += value
}
function operacao (value){
intro.value += value
}
function execute (operador, valor1, valor2){
var valor1 = Number(valor.value)
var valor2 = Number(valor.value)
if (operador == "+"){
var result = parseInt(valor1) + parseInt(valor2)
} else if (operador == "-") {
var result = parseInt(valor1) - parseInt(valor2)
} else if (operador == "/") {
var result = parseInt(valor1) / parseInt(valor2)
} else if (operador == "x") {
var result = parseInt(valor1) * parseInt(valor2)
}
return result
}
function calcular () {
resultado.innerHTML = execute()
}
You are calling the function
execute()
without passing any argument:resultado.innerHTML = execute()
– Sam
It also ignores the parameters valor1 and valor2 and takes such a value that does not exist.
– mari