Javascript validation calculator (I can’t find the error)

Asked

Viewed 157 times

0

Calculator

    <style type="text/css">
        #div1{
            text-align:center;
            border:1px solid black;
            width:20%;
            height:200px;
            position:absolute;
            left:40%;
        }

        #campo1,#campo2{
            width:40px;
            margin:5px;
        }

        #btn1,#btn2, #btn3, #btn4{
            margin:3px;
        }

        #result{                
            float:center;

        }
    </style>


    <script language="javascript">


        var num1 = parseInt(document.getElementById("campo1").value);
        var num2 = parseInt(document.getElementById("campo2").value);
        var soma = (num1+num2);
        var subtracao = (num1-num2);
        var multiplicacao = (num1*num2);
        var divisao = (num1/num2);

        function somar(){
            if(isNaN(num1) || isNaN(num2)){
                alert("Os campos devem conter apenas numeros");
            }
            else{
                document.getElementByID("valorFinal").innerHTML = soma;         
            }
        }

        function subtrair(){
            if(isNaN(num1) || isNaN(num2){
                alert("Os campos devem conter apenas numeros");
            }
            else{
                document.getElementByID("valorFinal").innerHTML = subtracao;            
            }
        }

        function multiplicar(){ 
            if(isNaN(num1) || isNaN(num2){
                alert("Os campos devem conter apenas numeros");
            }
            else{
                document.getElementByID("valorFinal").innerHTML = multiplicao;          
            }
        }

        function dividir(){ 
            if(isNaN(num1) || isNaN(num2){
                alert("Os campos devem conter apenas numeros");
            }
            else{
                document.getElementByID("valorFinal").innerHTML = divisao;          
            }
        }

    </script>
</head>
<body>
    <div id="div1">
    <h1>Calculadora</h1>

    <input type="text" id="campo1" />
    <input type="text" id="campo2" /><br />

    <input type="button" value="+" id="btn1" onClick="somar()">
    <input type="button" value="-" id="btn2" onClick="subtrair()">
    <input type="button" value="*" id="btn3" onClick="multiplicar()">
    <input type="button" value="/" id="btn4" onClick="dividir()"><br />

    <b><label id="result">Resultado: </label></b>

    <p id="valorFinal"></p>
    </div>
</body>

2 answers

3

When the browser reads these lines:

var num1 = parseInt(document.getElementById("campo1").value);
var num2 = parseInt(document.getElementById("campo2").value);

He immediately reads the value of these inputs and stores them in variables. He does this once and never again. So what happens is that when you "do the math" the values you might have written in the inputs are not in the variables num1 and num2. However, if you keep pointers to the element itself you can get the value later.

You have to update these values or each time you make an account or each time an input changes the value.

Doing a little DRY to the code could look like this:

var input1 = document.getElementById("campo1");
var input2 = document.getElementById("campo2");
var mostrador = document.getElementById("valorFinal");

function calculadora(fn) {
    var num1 = parseInt(input1.value, 10);
    var num2 = parseInt(input2.value, 10);
    if (isNaN(num1) || isNaN(num2)) alert("Os campos devem conter apenas numeros");
    else mostrador.innerHTML = fn(num1, num2);
}

function somar(a, b) {
    return a + b;
}

function subtrair(a, b) {
    return a - b;
}

function multiplicar(a, b) {
    return a * b;
}

function dividir(a, b) {
    return a / b;
}
 #div1 {
     text-align: center;
     border: 1px solid black;
     width: 40%;
     height: 200px;
     position: absolute;
     left: 40%;
 }
 
 #campo1,
 #campo2 {
     width: 40px;
     margin: 5px;
 }
 
 #btn1,
 #btn2,
 #btn3,
 #btn4 {
     margin: 3px;
 }
 
 #result {
     float: center;
 }
<div id="div1">
    <h1>Calculadora</h1>

    <input type="text" id="campo1" />
    <input type="text" id="campo2" />
    <br />

    <input type="button" value="+" id="btn1" onClick="calculadora(somar)">
    <input type="button" value="-" id="btn2" onClick="calculadora(subtrair)">
    <input type="button" value="*" id="btn3" onClick="calculadora(multiplicar)">
    <input type="button" value="/" id="btn4" onClick="calculadora(dividir)">
    <br />

    <b><label id="result">Resultado: </label></b>

    <p id="valorFinal"></p>
</div>

jsFiddle: https://jsfiddle.net/7k0mL6w7/

Note that the code as is should be at the end of <body> for Javascript to find the elements you are looking for in DOM.

-2

function calcular(valor, index) {

var num1 = document.getElementById("texto1").value

var num2 = document.getElementById("texto2").value


//var num1 = 10
//var num2 = 30


num1 = Number(num1)
num2 = Number(num2)


var soma = num1 + num2
var subtracao = num1 - num2
var multiplicacao = num1 * num2
var divisao = num1 / num2
//-------------------------------


if(isNaN(num1) || isNaN(num2)){
    alert("Os campos devem conter apenas numeros");
}

else if (index === "+") {


    let somar = document.getElementById('display').value = soma

    document.getElementById('display').value = somar


}

else  if (index === "-") {


    let subtrair = document.getElementById('display').value = subtracao

    document.getElementById('display').value = subtrair


}
else  if (index === "*") {


    let multiplicar = document.getElementById('display').value = multiplicacao

    document.getElementById('display').value = multiplicar


}
else  if (index === "/") {


    let dividir = document.getElementById('display').value = divisao

    document.getElementById('display').value = dividir
}

}

</script>
  • 1

    Welcome to Stack Overflow in English. This code may be a solution to the question, but your answer might be better if you [Edit] and include an explanation of the key points of the code. The goal Code-only answers - What to do?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.