0

I want to set maxlength in textarea. I have defined maxlength property in textarea but it seems to be of no use. Pls help. My code:

<html:textarea styleClass="textarea" maxlength="2100" cols="60" rows="3">
Priyesh Shah
  • 609
  • 2
  • 6
  • 8

3 Answers3

1

Try this javascript function:

$(function(){  
  $("#id").keypress(function() {  
    var maxlen = 100; //length as you desire
    if ($(this).val().length > maxlen) {  
      return false;
    }  
  })
});  
1

You have to write code for two events, keyup and copy paste so try this:

onKeyPress = "return ( this.value.length < 2100 );", onPaste = "return onTextAreaPaste(this,2100)"

Here is Js:

function onTextAreaPaste(textArea,size) {        
    var length = textArea.value.length;
    if(window.clipboardData!=undefined)
        length = textArea.value.length + window.clipboardData.getData('Text').length;
    return length < size;
}
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
1

I recently came across a problem with textarea maxlength attribute because the newlines where considered as 1 in Firefox, and 2 in IE and Chrome. So I decide to go for JavaScript for handling this.

Here is how I handle the max length, its a jquery plugin, very easy to set and there's no problem with the different behaviors of browsers, plus give you a feedback of the characters used.

Community
  • 1
  • 1
Carlos Escalera Alonso
  • 2,333
  • 2
  • 25
  • 37