» in my experience...

» home | about | contact | résumé
» archives | donate | rss syndication

»
»
NASA's Ion engine


Communiblog Communiblog expressed as RSS 2.0
Here at IMX
Memes R' Us
freetheaudio2.jpg
SuperNova 1987A from 1994 to 2003
GarageBand

Setting a maxlength on a textarea.
[ Posted by Dan on February 15, 2003 | 31 Comments ]

On a mailing list last week someone asked about placing a maxlength on a <textarea> which most HTML munkies will know is not a legal (or supported) attribute of that tag. Someone chimed in making that point and suggested that the person get familiar with the HTML 4.01 DTD. That advice is in the vein of 'if you teach a man to fish, you feed him for a lifetime.' I'm going to take the other tack and give the man a fish.

Most (all?) web browsers have onkeydown and onkeyup and onkeypress implemented as event handlers for the textarea tag. So we can use any of those to detect when a user is typing something into that field, and count the length of that field, and warn the user when they have passed an arbitrary maximum length that we choose. First, we make a <form>, a <textarea> and a place to show how many characters are remaining...

<form name="maxlength_test" action="who_cares" method="">
<TEXTAREA NAME="something" ROWS="10" COLS="50" onkeypress="textCounter(this,this.form.counter,255);"> </TEXTAREA> <br> <input type="text" name="counter" maxlength="3" size="3" value="255" onblur="textCounter(this.form.counter,this,255);"> characters remaining </form>

The form name doesn't matter because we use 'this' as a object model handle back to the form to operate on the elements within it. The name of the textarea does matter, so be sure you set that correctly. In the textarea, the onkeypress fires when a user pushes a key in and the key comes back up while typeing in the text area. The JavaScript function called "textCounter" gets a few variables passed to it. First, the textarea form object, the textarea's form object called 'counter' and a number. That number is the maximum length that the text area can be. The function looks like this...

function textCounter( field, countfield, maxlimit ) {
  if ( field.value.length > maxlimit )
  {
    field.value = field.value.substring( 0, maxlimit );
    alert( 'Textarea value can only be 255 characters in length.' );
    return false;
  }
  else
  {
    countfield.value = maxlimit - field.value.length;
  }
}
The function basically says if the textarea object that was passed in is longer than the number that was passed in, then set that textarea back to the length that we passed in, and alert the user about the maximum length. Otherwise, set the 'countfield,' which we passed into the function as "this.form.counter," to the maximum length minus the current length. Thus we get a count down.

And that's pretty much it. If you are using PHP or Mason or something, you can fill in the max length number in a variable, and let that get handled on an arbitrary basis. Pretty sweet. A working version of the text area is below, but first, note the following. I didn't write that JavaScript, Sprint did. I needed to set a max length of textarea for a project, so I found someone who did it already, and adapted it to my needs. This is a nice little bit of code that improves the usability of the form by informing you of any limits on data. Enjoy.


characters remaining

 

Normal Guy

have to have it check it onblur, too... and probably onsubmit as well. I just pasted in a few thousand characters and it took it.

Some browsers DO handle maxlength on textarea... I know this because I used it once a long while ago, not realizing it wasn't valid (and why isn't it, I'd like to know? It should be.) and it worked. but not reliably. I dont recall what browser it worked in. I think it was IE 4, this was back around the time 5 came out.

-Posted by jc on February 15, 2003 12:02 PM

I typically set it to onblur, onfocus, onkeydown and onkeyup. Then I set ononblur in the counter to reset itself to the normal number to demonstrate to the user that they can't alter that number and get more charaters in the textarea.

I figured for the sake of a little run thru of the functionality that demonstrating the javascript in a clean environment would be easiest (for me, hehe.)

-Posted by Dan on February 15, 2003 12:35 PM

Eric's First Rule of Web Programming: "NEVER trust the client".

Client being the combination of user and user-agent. The maxlength thing, as you mentioned, is not part of DTD, but its worth putting in there if you already have a bunch of other stuff that breaks it. The javascript thing is a good idea, because it works fine w/o scripting enabled.

However, a reminder that may seem like common sense to some of you and is news to a surprising number of web "programmers": ALWAYS always always check every parameter coming into a cgi. I've lost count of the number of times I've seen people setting sql strings directly request parameters because "we just let the browser do the validation". A followup to this reminder is to check not just for missing parameters, but for zero-length values on parameters, as browsers can post things differently. Again, you'd be surprised how many people don't do this.

Due to the snow, that concludes class for today.

-Posted by Eric on February 17, 2003 12:54 PM

"we just let the browser do the validation"

Isn't that MCSE for "oh well who needed that datbase anyway?"

-Posted by JC on February 17, 2003 01:20 PM

Normal Guy

database database database!
stupid typos. :-)

-Posted by JC on February 17, 2003 01:21 PM

just handling the textarea MAXLENGTH on keypress event wont handle the exception. what if i cut and paste into the TEXT AREA. you probably need to handle onblur event or on the final form submission

-Posted by hello on May 28, 2003 10:11 PM

that is a fantastic piece of code

-Posted by alan on June 11, 2003 06:55 AM

I am not able to Get this code working from php code
How do I call the Function.

My Code
<textarea rows=\"6\" cols=\"47\" style=\"width: 400px; height: 80px;\" name=\"idesc\" wrap=\"physical\">
onKeyUp=\"textCounter()\">$idesc</textarea>

----
As soon as I start entering there is a Error on Page
Please Help
Thanks

-Posted by Ram on July 17, 2003 03:57 PM

other way round...
just had the problem that i could not enter a long text in a textarea (about 6000 chars long - IE 5, Mac) - is this a known limitation or bug?


-Posted by bernhard on July 31, 2003 01:19 PM

Thanks for the code... Really worked well for what I am doing. Being new to this, I appreciate people like yourself that help other to learn.

Thanks!!!!
Scott

-Posted by Scott on August 3, 2003 09:29 PM

Appreciate your thoughtfulness in posting the code. It helped me out.

Regards,
Joe

-Posted by Joe Santilli on September 7, 2003 10:24 AM

This code works fine to count the length of the characters, and then set the end point, or MAX value. However, there is an issue if the user decides to backspace or delete some characters, the number in the "remaining characters" box is not updated. Any ideas on getting that thing to count backwards, or up as I delete the characters out of that box?

-Posted by NetDragon on October 10, 2003 05:24 PM

Uh, a spiffy way to implement a behavior on a control that needs one... is to use the behavior feature of CSS..

In a nut shell create a file say... maxlength.htc
and put the following code in it.

<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(!isNaN(maxLength))
{
maxLength = parseInt(maxLength);
var oTR = element.document.selection.createRange();
// Allow user to type character if at least one character is selected
if(oTR.text.length >= 1)
event.returnValue = true;
else if(value.length > maxLength-1)
event.returnValue = false;
}
}

// Cancel default behavior
function doBeforePaste()
{
if(!isNaN(maxLength))
event.returnValue = false;
}

// Cancel default behavior and create a new paste routine
function doPaste()
{
if(!isNaN(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>

Now either reference this in you control like so..
(I created a folder on my root called behaviors)
style="behavior:url(/behaviors/maxlength.htc)"
or reference it in you stylesheet if you want it global to the page.

textarea { behavior: url(/behaviors/maxlength.htc)}

and voila you have a behavior that also handles paste... RTFC

eidentity

[ ed. note: I edited this comment to ascape some html characters so they would show up correctly in the browser. No other mods were made. ]

-Posted by eidentity on December 10, 2003 12:04 PM

WOW!

-Posted by on December 21, 2003 09:46 AM

WOW!!!
never knew html/css can be this good.

-Posted by on January 5, 2004 02:17 PM

It did work. I have spend quite a good time to find the solutions but this is the best way to limit the text in a memo field.

Thanks for this good code.
Chet

-Posted by on January 22, 2004 03:47 PM

Thanks a ton!

-Posted by dee on January 23, 2004 03:30 AM

I tried this script, but it didn't count my first char.

I found this from a freeware contactform called hooble contact and it worked better for me.



function TrackCount(fieldObj,countFieldName,maxChars)
{
var countField = eval("fieldObj.form."+countFieldName);
var diff = maxChars - fieldObj.value.length;
if (diff {
fieldObj.value = fieldObj.value.substring(0,maxChars);
diff = maxChars - fieldObj.value.length;
}
countField.value = diff;
}

function LimitText(fieldObj,maxChars)
{
var result = true;
if (fieldObj.value.length >= maxChars)
result = false;

if (window.event)
window.event.returnValue = result;
return result;
}



Link description:





Chars left:


-Posted by Lene on February 12, 2004 06:38 PM

The html part disappeared..:O

-Posted by Lene on February 12, 2004 06:41 PM

I'll fix that later today (by escaping the html).

-Posted by Dan on February 13, 2004 09:34 AM

There will always be a defect to any code, and being able to prevent the problem before it occurs takes talent.

Before I read the posts, I tried several things.. copy and paste, backspace, etc. Aha! A defect. Either way, the general idea behind the code works, yet minor setbacks could be worked out...

however, Nice work all.

Continue programming...

-Posted by on February 23, 2004 09:31 AM

Good but if you cut & paste it goes past the char limit. I placed validation on the onsubmit event and reused the code there and it worked fine.

-Posted by on February 24, 2004 12:28 AM

I hate javascript...

Is the most annoying, useless and time-wasting invention ever saw...

It's like saying, ok let's cut costs by using just two digits for the date, what a great idea...

People using onblur events on form should be shot


Greetings...

-Posted by want to be anonymous on March 1, 2004 07:02 AM

test

-Posted by test on March 9, 2004 06:09 PM

What is the easiest way to implement multiple textarea counters, per page? This script works fine for a single textarea, but I have a page that has multiple textarea inputs, that I would like counters for, and I am wondering if anyone has done something like this with this code.

TIA!

- Bruce

-Posted by Bruce Garlock on April 1, 2004 02:28 PM

Thanks Dan for your textarea javascript function it helped me out with a flash app I'm building which pulls textarea form results into the flash movie. You da man.


Cheers
Chris Glubish
Somnia Inc.
EBusiness Solutions
http://www.somnia.ca
Edmonton, Alberta Canada

-Posted by Chris Glubish on April 12, 2004 08:28 PM

Hi eidentity!
I´ve seen ur sample somewhrre else, questin is that it´s not working on my site.. I´ve created the .htc file but am ot sure of how to tell the to use it?
should it be like this:
< textarea class='input' name="aname" maxLength="20" { behavior: url(maxlength.htc)} >

ok, will wait 4 your answer.. .thanx a lot in advance!

-Posted by Diego on May 11, 2004 02:14 PM

I believe the behavior attribute in css is internet explorer exclusive. Dont use it.

-Posted by David Hellsing on May 26, 2004 08:57 AM

Great Code.

-Posted by JS on August 11, 2004 07:10 PM

Normal Guy

Diego: try style="behavior: url(maxlength.htc)" instead, I've never even seen the curly braces method before.

Beware that IE 5 (atleast 5.5) and above (atleast IE 6) have serious problems with behaviors - major memory leakage and execution lag when many behaviors are loaded. When using only a few behaviors on a page the problem isn't noticable, but try using a hundred or so and you'll see.

-Posted by Boggle on September 7, 2004 04:29 AM

Oh, just read eidentity's post again and saw where the curly braces came from, it's for use in a stylesheet ofcourse. Diego, you're confusing css stylesheet and html attribute syntax. :)

-Posted by Boggle on September 7, 2004 04:47 AM




Comment posting has been turned off because I don't have enough time and will to deal with the constant comment spamming. I'm very sorry and will fix this sometime soon (soon = before 2004 ends).

MovableType AmphetaDesk
NetNewsWire BlogTree Subscribe with Bloglines RSS Feed
Copyright © 2001 - 2003 by Daniel Kapusta