Wednesday, March 19, 2008

How To Set TextArea Max Length


<html>
<head>
<script type="text/javascript" language="javascript">
function chkLength(evt,len)
{
var str = document.getElementById(evt.id);
if(str.value.length < len)
{
return true;
}
else
{
return false;
}
}
</script>

</head>
<body>
<textarea id="txtArea" rows=5 cols=40 onkeypress="return chkLength(this,100);" ></textarea>
</body>


Program Demo
Note:IE Supported


4 comments:

Anonymous said...

Nice, make sure you check onpaste also:

scripts:
// Keep user from entering more than maxLength characters
function maxLength(field,maxChars)
{
return (field.value.length <= maxChars);
}
// Keep user from entering more than maxLength pasted characters
function maxLengthPaste(field,maxChars)
{
event.returnValue=false;
if((field.value.length + window.clipboardData.getData("Text").length) > maxChars)
{
return false;
}
event.returnValue=true;
}


Then add these to the textarea:
onKeyPress="return maxLength(this,'255');" onpaste="return maxLengthPaste(this,'255');"

Anonymous said...

Minor change to the scripts:

// Keep user from entering more than maxLength characters
function maxLength(field,maxChars)
{
return (field.value.length < maxChars);
}
// Keep user from entering more than maxLength pasted characters
function maxLengthPaste(field,maxChars)
{
event.returnValue=false;
if((field.value.length + window.clipboardData.getData("Text").length) > maxChars)
{
return false;
}
event.returnValue=true;
}

Anonymous said...

Great Work Friend

Anonymous said...

One problem, however. What do you do when the user finds out he/she has typed too much and wants to go back and edit what was written? Every key press after this is being ignored.

You could substring the field but that would allow the user to see the last typed char a bit before it disappears, so a more proper way is needed

Creative Commons License
Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.