简体   繁体   中英

why do i get NaN when i try to multiply these numbers?

i try to multiply two numbers and show the result in a textbox but i get NaN when i click the button.

var firstBox=parseFloat(document.getElementById('firstTxt').value);
    var secondBox=parseFloat(document.getElementById('secondTxt').value);
    var the_answer=document.getElementById('answer');
    var calculate=document.getElementById('btn');
    
    calculate.onclick=function(){
      var result= firstBox*secondBox;
      the_answer.value=result;
    }
    
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>title</title>
      </head>
      <body style="background-color: cadetblue;">
      <p><input type="text" id="firstTxt"/> </p>
      <p><input type="text" id="secondTxt"/> </p>
      <p><input type="button" id="btn" value="Calculate"> </p>
      <p><input type="text" id="answer"/> </p>
    <script src="practice.js"></script>
      </body> 
    </html>

The firstBox and secondBox variables does not updates it's values when inputs changes.

So move/copy below lines inside of onclick handler:

var firstBox=parseFloat(document.getElementById('firstTxt').value);
var secondBox=parseFloat(document.getElementById('secondTxt').value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM