Skip navigation

Tag Archives: textarea

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(){

        $("#remarks").bind("keydown keyup", function(e){

    return {
        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??


Note few points regarding <textarea>

  • Initial value must be enclused between <textarea> and </textarea>.
  • maximum number of characters not allowed.

i.e., it is wrong to use. Strict xhtml validation will fail because of maxlength.
<textarea rows=”3′ cols=”20″ maxlength=”150″ />

if not worried about validation, then add maxlength property and call onkeypress as follows
<textarea rows=”10” cols=”25” maxlength=”150” onkeypress=”return TextUtil.isNotMax(this)”></textarea>

var TextUtil = new Object();
TextUtil.isNotMax = function(oTextArea) {
return oTextArea.value.length != oTextArea.getAttribute(“maxlength”);

Now you got maxlength property to textarea. hurray!!