Captcha using javascript

Basically we add captcha on form to stop spamming mail. I have used JavaScript captcha which I have mentioned below. May be it can help some one:

Add this code before submit button.

<form action=”thankyou.php” method=”post” name=”myform” onsubmit=”return checkForm();”>
<div class=”row”>
<div class=”col-md-6″>
<label>Please Enter Security Code*:</label><div id=”txtCaptcha”></div>
<input type=”text” name=”code” id=”txtInput” />
<span id=”ctcha” class=”commonerror”></span></div>
</div>
<input type=”submit” value=”Submit” />
</form>

 

//Created / Generates the captcha function
function DrawCaptcha()
{
var a = Math.ceil(Math.random() * 8)+ ”;
var b = Math.ceil(Math.random() * 8)+ ”;
var c = Math.ceil(Math.random() * 8)+ ”;
var d = Math.ceil(Math.random() * 8)+ ”;
var e = Math.ceil(Math.random() * 8)+ ”;

var code = a + b + c + d + e;
document.getElementById(“txtCaptcha”).innerHTML = code;
}
// Validate the Entered input aganist the generated security code function
// Remove the spaces from the entered and generated code
function removeSpaces(string)
{
return string.split(‘ ‘).join(”);
}

function checkForm()
{
var str1 = removeSpaces(document.getElementById(‘txtCaptcha’).innerHTML);
var str2 = removeSpaces(document.getElementById(‘txtInput’).value);
if (str1 == str2)
return true;
document.getElementById(“ctcha”).innerHTML=’Please enter correct code!’;
document.myform.txtInput.focus();
return false;

}
window.onload = DrawCaptcha();