Skip navigation

Monthly Archives: July 2012


Here is the cross browser javascript code to fix the maxlength property of textarea

Basic html structure
<!-- html structure used -->
<textarea id="remarks" name="remarks" maxlength="20" rows="5" cols="50"></textarea>
<div class="charLeft">characters left:20</div>
<!-- -->

CSS used

/* css used */
.​charLeft​ {color:#ccc;}​
/*  */
// Javascript code used
var restrictCharacters = (function(){

    $(function(){
        $("#remarks").bind("keydown keyup", function(e){
            restrictCharacters.checkRemarksLength($("#remarks"),e);
        });
    });

    return {
        remarks:"",
        checkRemarksLength: function(field,e){
            var curLength = field.val().length,
                maxLength = parseInt(field.attr('maxlength')),
                iam = field.attr('name');
            if(e.type == 'keydown'){
                if(curLength > maxLength) return false;
                else this.remarks= field.val();
            }
            if(e.type == 'keyup') {
                if(maxLength - curLength >= 0) $('.charLeft').html('Charecters left: '+(maxLength-curLength));
                else field.val(this.remarks);
            }
        }
    }
})();
// 

Want to play around??

Advertisements