简体   繁体   中英

Cannot access value in input field with document.getElementById

I cannot access a value from an input field with document.getElementById to check if the input number is even or odd.

Could you please tell me what is wrong with my code?

Thank you in advance!

<!DOCTYPE html>
    <html>
        <head>
            <title>Even or odd</title>
            <meta charset="utf-8"/>
            <link href="style.css" rel="stylesheet"/>
        </head>
        <body>

            <form>
                <p>Please type a number in the field and press the button to check if this is an even or an odd number.</p>
                <input type="text" id="num" placeholder="Enter a number"/>
                <button type="button" onclick="myFunction()">Click Me!</button>                             
            </form>


            <script>
                var a = parseInt(document.getElementById("num").value);
                function myFunction(){  if ((a/2)==%){
                                            alert("The number is odd");
                                        } else {
                                            alert("The number is even");
                                        }

                                    }



            </script>

        </body>
    </html>

You need to move that line of code that fetches the value inside the function. As it is, that only runs once, when the page loads.

          function myFunction(){  
            var a = parseInt(document.getElementById("num").value);

Also, I don't know what (a/2) == % is supposed to mean, but it's a syntax error.

            if (a % 2 != 0) // odd test
            if (a % 2 == 0) // even test 

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