Simplified captcha and a helper JS

I am using a simplified captcha code as follows.

protected/components/CaptchaAction.php:




<?php

class CaptchaAction extends CCaptchaAction

{

        /**

         * @var integer how many times should the same CAPTCHA be displayed. Defaults to 3.

         */

        public $testLimit=1;

        /**

         * @var integer the default length for randomly generated word. Defaults to 6.

         */

        public $defaultLength=6;


        /**

         * Generates a new verification code.

         * @return string the generated verification code

         */

        protected function generateVerifyCode()

        {

                $length=$this->defaultLength;

                $letters='0123456789';

                $code='';

                for($i=0;$i<$length;++$i)

                {

                        $code.=$letters[rand(0,9)];

                }

                return $code;

        }

}



and a helper JS as follows.

js/captcharequest.js:




$(document).ready(function() {

var $s='Please input six columns of integers shown above';

var $c='gray';

$('#captcha-input').css('color',$c);

$('#captcha-input').attr('value',$s);

$('#captcha-input').css('width','210');

$('#captcha-input').focus(function() {

	$('#captcha-input').css('color','black');

	if ($('#captcha-input').val()==$s) {

	    $('#captcha-input').attr('value','');

	}

    });

$('#captcha-input').blur(function() {

	if (!$('#captcha-input').val()) {

	    $('#captcha-input').css('color',$c);

	    $('#captcha-input').attr('value',$s);

	}

    });

});



In order to enable this JS, include following line in ‘protected/views/layouts/main.php’




Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl.'/js/captcharequest.js', CClientScript::POS_HEAD);



And the last thing is to attach the id to the input field.




          <td class="box"><?php echo CHtml::activeTextField($model,'authcode',array('class'=>'inputtext',

                                         'id'=>'captcha-input')); ?></td>



Hope this may be of any help to you. :)