简体   繁体   中英

Why does my previous function don't work when I add a new function? How can I fix this?

So generateOTP() should give me a random number and it will display above the text "Enter the Number Above" it works but after I add my second function it disappears. What the program is supposed to do is display a random number, then you input the number next when the number matches the random number given it will give a message "Your answer matches the number above" and otherwise Your answer does not match the number above." Please help

<html>
    <head>
        <title>Simulating One-Time-Password (OTP) or CAPTCHA</title>
        <meta charset="UTF-8">
        <meta name="description" content="Simulating One-Time-Password (OTP) or CAPTCHA">
        <meta name="keywords" content="java, otp">
        <meta name="author" content="sad">

        <style>
        </style>

        <script>
            function generateOTP() { 

                // Declare a digits variable  
                // which stores all digits 
                var digits = '0123456789'; 
                let OTP = ''; 
                for (let i = 0; i < 6; i++ ) { 
                    OTP += digits[Math.floor(Math.random() * 10)]; 
                } 
                return OTP; 

            } 
                document.write("OTP of 6 digits: ") 
                document.write( generateOTP() );
                var ranNum = generateOTP();

            function checkValue(){
                var finalAnswer =
                document.getElementById("answer").value;

                if (ranNum== finalAnswer) {
                    document.write("Your answer matches the number above")

                    else{
                        document.write("Your answer does not match the number above")
                    }

                }
            }
        </script>

    </head>

    <body>
        <p> Enter the number above
            <input id="answer" type="text"/>
        </p>
        <p>
            <button onclick="checkValue()"> Display  </button>
        </p>
    </body>

</html>

You have your else keyword within the if statement. It should be:

if (condition) {
    // do something
} else {
    // do something else
}

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