почему я получаю NaN, когда пытаюсь умножить эти числа?

#javascript

#javascript

Вопрос:

я пытаюсь умножить два числа и показать результат в текстовом поле, но я получаю NaN, когда нажимаю кнопку.

 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=resu<
    }
    
    
    <!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>
  

Ответ №1:

Переменные firstBox and secondBox не обновляют свои значения при изменении входных данных.

Поэтому переместите / скопируйте нижеприведенные строки внутри обработчика onclick:

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