In this tutorial you will get JavaScript captcha example.
Captcha is used to determine whether or not the user that is filling and submitting a web form is human. While developing web projects we often require to add captcha feature.
So here I have shared the simplest way to create captcha in JavaScript. It will look like as shown in below image.
JavaScript Captcha Example
The below code generates a 4 digits captcha in JavaScript.
<html> <head><title>JavaScript Captcha Example</title></head> <body onload="generateCaptcha()"> <script> var captcha; function generateCaptcha() { var a = Math.floor((Math.random() * 10)); var b = Math.floor((Math.random() * 10)); var c = Math.floor((Math.random() * 10)); var d = Math.floor((Math.random() * 10)); captcha=a.toString()+b.toString()+c.toString()+d.toString(); document.getElementById("captcha").value = captcha; } function check(){ var input=document.getElementById("inputText").value; if(input==captcha){ alert("Equal"); } else{ alert("Not Equal"); } } </script> <input type="text" id="captcha" disabled/><br/><br/> <input type="text" id="inputText"/><br/><br/> <button onclick="generateCaptcha()">Refresh</button> <button onclick="check()">Submit</button> </body> </html>
Explanation
In above script the generateCaptcha() function is used to generate the captcha as the page loads. This is done by the onload attribute in body tag. Inside generateCaptcha() we have used Math.floor((Math.random() * 10)) to generate a random number between 1 (included) and 10 (excluded). In this way we generate for random numbers and then join them to form a string. The toString() method is used to convert number to string. Now we set this string as value of captcha textbox.
When Submit button is clicked the check() function is called that checks whether the entered captcha matches with original captcha or not. If they match, “Equal” alert is displayed otherwise “Not Equal” alert is displayed.
The Refresh button is used to regenerate the captcha.
The above JavaScript captcha code is easy to understand, still if you are facing any problem then comment below.
The post JavaScript Captcha Example appeared first on The Crazy Programmer.