views:

522

answers:

4

Textarea validation,

How to limit the characters in a textarea for not exceeding more than 50 characters.

<textarea rows="5" cols="15"></textarea>

Thanks.....

+3  A: 

One Google away.

<script language="javascript" type="text/javascript">
<!--
function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}
-->
</script>

Implementation:
<textarea name="myName" onkeypress="return imposeMaxLength(this, 50);" ></textarea> 

EDIT:

Code that doesn't freeze text:

<script type="text/javascript">

/***********************************************
* Textarea Maxlength script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function imposeMaxLength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}

</script>

<textarea maxlength="40" onkeyup="return ismaxlength(this)"></textarea>
Marcus L
I had tried this,the code limits the characters though but then the data is frozen,i.e, the data cannot be edited or deleted..
Hulk
I had some problems testing, editing so you've got a `</textarea>`
ILMV
True. Added a different solution - thought not as good looking considering it let's you write the char, then deletes it.
Marcus L
This won't prevent the user from pasting in as much text as they like.
Tim Down
+7  A: 

Using:

<textarea rows="5" cols="15" maxlength="50"></textarea>

From http://sigswitch.com/2008/07/textarea-maxlength-with-jquery/:

  $(document).ready(function(){
     $('textarea[maxlength]').keyup(function(){
      var max = parseInt($(this).attr(’maxlength’));
      if($(this).val().length > max){
       $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
      }

      $(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
     });
    });
zaf
Thanks for the link, [I made a better version](http://sigswitch.com/2010/04/updated-textarea-maxlength-with-jquery-plugin/) of this as a jquery plugin.
Matt
This won't work when the user drags text into the textbox.
rahul
@rahul The updated version does, see the demo: http://jsbin.com/ufuji3/9
Matt
A: 

I don't know of a built in HTML way but you can use this:

<textarea rows="5" cols="15" onkeydown="return validateCharLimit(this);"></textarea>​​​​​​​​​​​​​​

function validateCharLimit(area) 
{
    var limit = 50;
    var iChars = area.value.length;
    if (iChars > limit) {
        return false;
    }
    return true;
}
Dror
A: 
<script>
function chkLen()
{
var tlen=document.getElementById('myTA').value.length;
if(tlen>50)
{
document.getElementById('myTA').value.substr(0,49)
}
}
</script>

<body>
    <textarea id="myTA" onkeyup='chkLen()'></textarea>
</body>
nik