How to Create Math Captcha in Javascript

Math Captcha in Javascript

In this example, We will show you simple program about, How to create Math Captcha in Javascript. The example program has been tested and shared in the same post.

Script Code

    
    var a, b;

    function getRandom() {

        var numbers = new Array();

        for(var i=1;i<100;i++) {
            numbers.push(i);
        }

        a = numbers[Math.floor(Math.random() * numbers.length)];
        b = numbers[Math.floor(Math.random() * numbers.length)];

        document.getElementById("firstNumber").innerHTML = a;
        document.getElementById("secondNumber").innerHTML = b;

    }

    function check() {

        var result = document.getElementById("result").value;

        if(result == (parseInt(a) + parseInt(b))) {
            alert("Correct");
        } else {
            alert("Wrong");
        }
    }

Complete Example

<html>
    <head>
        <title>Sample Math Captcha in Javascript</title>
    </head>

    <body onload="getRandom();">
       
        <p>
            <span id="firstNumber"></span>
            +
            <span id="secondNumber"></span>
            =
            <input type="text" id="result"/>
            <input type="button" value="Check" onclick="check();" />
        </p>
        
        
        <script>
            var a, b;

            function getRandom() {
                var numbers = new Array();
                for(var i=1;i<100;i++) {
                    numbers.push(i);
                }
                a = numbers[Math.floor(Math.random() * numbers.length)];
                b = numbers[Math.floor(Math.random() * numbers.length)];
                document.getElementById("firstNumber").innerHTML = a;
                document.getElementById("secondNumber").innerHTML = b;
            }

            function check() {
                var result = document.getElementById("result").value;
                if(result == (parseInt(a) + parseInt(b))) {
                    alert("Correct");
                } else {
                    alert("Wrong");
                }
            }

        </script>
    </body>
</html>

Output

Math Captcha in Javascript

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.