javascriptgetelementbyidparseint

not ready getElementById


When I am entering a number into the input, the result is coming back as NaN, even I parseInt the result. I also tried with a string and it is not reading it either.

Please advise on why it is not reading the input.

Thank you, Avi

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" id="mult">Submit</button>

<p id="demo"></p>

<script>

var first = parseInt(document.getElementById('numb').value, 10);

document.getElementById('mult').addEventListener('click', multiply);

function multiply() {
    console.log(first);
}

</script>

Solution

  • You need to define first inside your multiply() function

    <!DOCTYPE html>
    <html>
    <body>
    
    <h2>JavaScript Validation</h2>
    
    <p>Please input a number between 1 and 10:</p>
    
    <input id="numb">
    
    <button type="button" id="mult">Submit</button>
    
    <p id="demo"></p>
    
    <script>
    
    document.getElementById('mult').addEventListener('click', multiply);
    
    function multiply() {
       var first = parseInt(document.getElementById('numb').value, 10);
       console.log(first);
    }
    
    </script>