Solved

set Maxlength to TextArea

Posted on 2003-10-29
13
133,743 Views
Last Modified: 2011-08-18
Hi
I am using Textarea type.I want to set maximum length to the textarea.
I am using following code for the same,but it is not working,
<textarea name="txtDescription" cols=10 rows=3 maxlength=50></textarea>
But it is not working,it takes chars beyond 50 also.
Help me inthe same

0
Comment
Question by:chitramahadik
13 Comments
 
LVL 31

Expert Comment

by:seanpowell
ID: 9640628
Hi, you're best bet is to set this in a basic javscript function, like so:

<html>
<head>
<title>Category</title>
<script language="javascript" type="text/javascript">
<!--
function validate() {
      maxlength=50;
      if(document.myForm.theTextArea.value.length>=maxlength) {
            alert('Your comments must be 50 characters or less');
            document.myForm.theTextArea.focus();
            return false;
      } else {
            return true;
      }
}
//-->
</script>
</head>
<body>
<form name="myForm" onsubmit="return validate();">
Comments:<br />
<textarea name="theTextArea" cols="10" rows="3"></textarea><br />
<input type="submit">
</form>
</body>
</html>


How to Customize
============

Make sure that you change the following 2 values to suit your page, both in the javascript, and the form:

1. myForm
2. theTextArea

If the name of your form is hello and the name of your text area is goodbye, then the code above would be:

function validate() {
      maxlength=50;
      if(document.hello.goodbye.value.length>=maxlength) {
            alert('Your comments must be 50 characters or less');
            document.hello.goodbye.focus();
            return false;
      } else {
            return true;
      }
}

and

<form name="hello" onsubmit="return validate();">
Comments:<br />
<textarea name="goodbye" cols="10" rows="3"></textarea><br />
<input type="submit">
</form>

Thanks
0
 

Author Comment

by:chitramahadik
ID: 9640658
Hi,I knew it can work instead if I called the same javascript function onChange event of TExtarea ,it will work but I can't specify maxlength=50 to TextArea object,the same is working for Text object.
0
 
LVL 31

Expert Comment

by:seanpowell
ID: 9640681
That's because the textarea object does not use the "maxlength" property. It only supports the attributes: columns, rows, and name.
0
 
LVL 3

Accepted Solution

by:
DelTreme earned 20 total points
ID: 9648918
I've got a script to add the MaxLength property to the TEXTAREA tag (I didn't write it, found it somewhere on the net):

You'll need a file, called     maxlength.htc (code below)    wich adds a behaviour to the TextArea tag.

In your stylesheet, add:

TEXTAREA { behavior: url(maxlength.htc);}

From that point on, you can use
<TEXTAREA MAXLENGTH=50></TEXTAREA>
Whereever you want.

---code for maxlength.htc---
<PUBLIC:COMPONENT id="bhvMaxlength" urn="maf:Maxlength">
      <PUBLIC:PROPERTY name="maxLength" />
      <PUBLIC:ATTACH event="onkeypress" handler="doKeypress" />
      <PUBLIC:ATTACH event="onbeforepaste" handler="doBeforePaste" />
      <PUBLIC:ATTACH event="onpaste" handler="doPaste" />

<SCRIPT language="JScript">
// Keep user from entering more than maxLength characters
function doKeypress(){
      if(maxLength && value.length > maxLength-1){
            event.returnValue = false;
            maxLength = parseInt(maxLength);
      }
}
// Cancel default behavior
function doBeforePaste(){
      if(maxLength)
            event.returnValue = false;
}
// Cancel default behavior and create a new paste routine
function doPaste(){
      if(maxLength){
            event.returnValue = false;
            maxLength = parseInt(maxLength);
            var oTR = element.document.selection.createRange();
            var iInsertLength = maxLength - value.length + oTR.text.length;
            var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
            oTR.text = sData;
      }
}
</SCRIPT>

</PUBLIC:COMPONENT>
0
 

Expert Comment

by:kingromes
ID: 11252970
I assume that is an IE-only solution (Tested in Mozilla Firefox).

Neat trick tho'
0
 

Expert Comment

by:nishaj
ID: 11541955
I could not make this work using IE6/javascript. Maybe I am doing something wrong.

Added the line to the css as above to add the behavior to TEXTAREA.

Added the htc file with the code from above - just changed the SCRIPT LANGUAGE = Javascript.

Used the input tag as <TEXTAREA MAXLENGTH=5> as a test.

It just doesn't do anything.

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 3

Expert Comment

by:gfdos
ID: 11975224
I found this on the net, and it seems to fix the problems described herein:

<script language="jscript">
function LimitMultiLineLength(obj)
{
 var iKey;
var eAny_Event = window.event;
iKey = eAny_Event.keyCode;
var re
re = new RegExp("\r\n","g")  
x = obj.value.replace(re,"").length ;
if ((x >= obj.maxLength) && ((iKey > 33 && iKey < 255) || (iKey > 95 && iKey < 106)) && (iKey != 13))
{
if (obj.ErrorMessage )
{
alert(obj.ErrorMessage);
}
window.event.returnValue=false;       
}
}
</script>

called like this:

<textarea name="name" id="name" onkeypress="LimitMultiLineLength(this)" onbeforepaste="LimitMultiLineLength(this)" maxLength="255" ErrorMessage="The maximum allowance of 255 characters has been reached." style="height:108px;width:400px;"></textarea>
0
 

Expert Comment

by:bharatpanthee
ID: 12839037
there is no property like maxlengh in textarea u can use javascript for check this
code for this
<script language="javascript">
var text1;
function checklength(i)
{
var txt;
txt=document.form.textarea1.value;
n=txt.length;
if (n>i) //i is the maxlength of textarea which we have set to 80
{
alert('Text overflow');
document.form.textarea1.value=text1;
return;
}
text1=document.form.textarea1.value;
}
</script>

<body>
<form>
<textarea name=textarea1 onkeydown="javascript:checklength(80)"></textarea>

</form>
</body>


I think this will help u.
0
 

Expert Comment

by:biffsmith
ID: 13458808
The validate() works like a charm.  Thank you!  Now what if the form contains more than one textarea? I attempted to add additional variables to the script but I'm certain I have the syntax wrong:

<script language="javascript" type="text/javascript">
<!--
function validate() {
     maxlength=200;
     if(document.form.comments1.value.length>=maxlength) {
          alert('Your comments must be 200 characters or less');
          document.form.comments1.focus();
          return false;
     } else {
          return true;
     }
}
function validate1() {
     maxlength=200;
     if(document.form.comments2.value.length>=maxlength) {
          alert('Your comments must be 200 characters or less');
          document.form.comments2.focus();
          return false;
     } else {
          return true;
     }
}
function validate2() {
     maxlength=200;
     if(document.form.comments3.value.length>=maxlength) {
          alert('Your comments must be 200 characters or less');
          document.form.comments3.focus();
          return false;
     } else {
          return true;
     }
}
//-->
</script>

AND THEN IN THE FORM TAG, I CALLED IT AS SUCH:

onsubmit="return validate(); return validate1(); return validate2()"

Since it doesn't work I'm sure I've got it wrong.  Can you take it one step further and advise as to the correct syntax?  Will this even work with more than one textarea field?

Thank you!
0
 

Expert Comment

by:presbria
ID: 14646093
Hey, I know this one's already solved, but I have an alternative solution that I feel is better for a few reasons.  

#1 It's re-usable for all text areas via one function
#2 It doesn't inform teh user that he/she is typing too many characters, it prevents them from doing so, sort of like maxlength

There's a downside: the user can see the typed character for an instand prior to the removal.

Here's the function:

function CheckMaxLength(Object, MaxLen)
{
  if(Object.value.length > MaxLen)
  {      
    Object.value = Object.value.substring(0, MaxLen);
  }
}

And the implementation:
<textarea name="Responsibilities" onkeyup="CheckMaxLength(this, 15);"><textarea>


Passing the form object and using it's methods.  Pretty simply and painless.


 
0
 

Expert Comment

by:presbria
ID: 14646099
Oh, that answered both questions too!!!

I know, I'm too late, but I think it's still the best way to do it, if not, please let me know a better one.

Thx.
0
 

Expert Comment

by:mdmeighan
ID: 14728033
This is a little cleaner - it imposes the length limit by cancelling the extra keypresses rather than using the substring() trick --

function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}

Implementation:


<textarea name="myName" onkeypress="return imposeMaxLength(this, 15);" ><textarea>
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Someone recently asked me about how to display a progress indicator on a page while an iframe is loading. And I remember when I first came across this myself. It was a bit tricky to get my head around, but really, it's very simple. The most impor…
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
In this tutorial viewers will learn how to position items using CSS's three positioning types Create a new HTML document with an internal stylesheet.: Create another div in CSS and name it Absolute : Type "position:absolute;" and "top:10px; left:50p…
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now