Why does NaN output?

  • 0
    var input1 = parseInt(document.getElementById("input1"));
    var input2 = parseInt(document.getElementById("input2"));
    var button = document.getElementById("button");
    
    button.onclick = function(){
        var result = input1 + input2;
        document.body.append(result);
    }


    <input type="text" id="input1">
        <h2>+</h2>
        <input type="text" id="input2"><br>
        <button id="button">=</button>
    JavaScript Ronan Ware, Aug 20, 2020

  • 2 Answers
  • 0
    Because you get the values ​​when the fields are still empty, and by pressing the button you just use them, you need to get them by pressing the button, besides, the input itself is not parsed into int, you need to parse its value property:
    var input1 = document.getElementById("input1");
    var input2 = document.getElementById("input2");
    var button = document.getElementById("button");

    button.onclick = function(){
    var result = parseInt(input1.value) + parseInt(input2.value);
    document.body.append(result);
    }
    Anonymous

  • 0
    because input1 and input2 get values ​​(and not correct) when the page loads, and not when you click on the button



    var button = document.getElementById("button");

    button.onclick = function(){
    var input1 = parseInt(document.getElementById("input1").value);
    var input2 = parseInt(document.getElementById("input2").value);
    var result = input1 + input2;
    document.body.append(result);
    }
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!