Derivan Posted February 3, 2022 Share Posted February 3, 2022 <!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> 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 More sharing options...
Ingolme Posted February 3, 2022 Share Posted February 3, 2022 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. 1 Link to comment Share on other sites More sharing options...
Derivan Posted February 3, 2022 Author Share Posted February 3, 2022 Thank you very much I changed the code by placing the number variables inside the functions the code was a little big but it works, Thank you Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now