Jump to content

JavaScript error math operations


Derivan

Recommended Posts

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <H1> Calculadora</H1>
    <input type="button" value="Adição" onclick="adc()">
    <input type="button" value="Subtração" onclick="sub()">
    <input type="button" value="Mutiplicação" onclick="mult()">
    <input type="button" value="Divisão" onclick="dv()"> <br>
    <input type="number" name="nn1" id="nn1">
    <input type="number" name="nn2" id="nn2">
    <div id="resp">Resultado</div>
    <script>
        var ns1 = window.document.querySelector('input#nn1')
        var ns2 = window.document.querySelector('input#nn2')
        var res = window.document.querySelector('div#resp')
        var n1 = Number(ns1.value)
        var n2 = Number(ns2.value)
        function adc(){
            var soma = n1 + n2
            res.innerHTML = soma
        }
        function sub(){
            var sub = n1 - n2
            res.innerHTML = sub
        }
        function mult(){
            var mult = n1 * n2
            res.innerHT = mult
        }
        function dv(){
            var divz = n1 / n2
            res.innerHTML = divz
        }
    </script>
</body>
</html>

382217036_Capturadetela2022-02-03140947.thumb.png.2e5f0da72b9d439877262307a540d9e2.png

hello, can someone help me this code was to do math operations but the first 3 buttons return 0 and the last NaN, can someone tell me where is the error?

Link to comment
Share on other sites

The variables n1 and n2 haven't been updated since the page first loaded. Which means that the fields were empty and they don't have a value.

You need to set these values inside the function calls so that they get updated to the correct values when the button is clicked.

  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...