Saturday, May 24, 2014

Generate captcha using Javascript

Hi friends.In this post i am going to show how to create captcha using Javascript.

The captacha code is creating using onload() function.And i have used two math function to create captcha.

1.Math.ceil
    The ceil() method rounds a number UPWARDS to the nearest integer, and returns the result.

2.Math.random
    The random() method returns a random numbers.

Javascript Functions

<script type="text/javascript">

   //Created / Generates the captcha function  
    function DrawCaptcha()
    {
        var a = Math.ceil(Math.random() * 9)+ '';
        var b = Math.ceil(Math.random() * 9)+ '';     
        var c = Math.ceil(Math.random() * 9)+ '';
        var d = Math.ceil(Math.random() * 9)+ '';
        var e = Math.ceil(Math.random() * 9)+ '';
        var f = Math.ceil(Math.random() * 9)+ '';
        var g = Math.ceil(Math.random() * 9)+ '';
        var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
           document.getElementById("txtCaptcha").value = code;
        document.getElementById("txtCaptchaDiv").innerHTML = code;
    }

    // Remove the spaces from the entered and generated code
    function removeSpaces(string)
    {
        return string.split(' ').join('');
    }
  

</script>

HTML Form

  <form method="post" action="#" id="form1" name="form1">
      <table cellspacing="0" cellpadding="2" border="0">
        <tbody>
          <tr >
            <td class="style1">Enter This Code <span style="color:#F30">*</span></td>
            <td colspan="2" style="margin-top: 10px;display: block;margin-bottom: 10px;"><span id="txtCaptchaDiv"></span></td>
          </tr>
          <tr>
            <td>&nbsp;</td>
            <td colspan="2"><input type="hidden" id="txtCaptcha" />
            </td>
          </tr>
        </tbody>
      </table>
    </form>
Please share your comments and feebback.Thanks.Please subscribe my updates via email.

No comments:

Post a Comment