[thelist] TIP: Limiting TextArea length

John.Brooking at sappi.com John.Brooking at sappi.com
Wed Mar 17 13:07:44 CST 2004


<tip author="John Brooking" type="Limiting textarea length">

   The TEXTAREA tag does not have a MAXLENGTH attribute the way that an
INPUT tag does, at least not in most standard browsers. A very simple and
effective way to limit the number of characters that can be *typed* into a
TEXTAREA tag is:
   
   <textarea onKeyPress="return ( this.value.length < 50 );"></textarea>
   
   This works because the boolean expression compares the field's length
before the new character is added to the maximum length you want (50 in this
example, use your own here), and returns true if there is room for one more,
false if not. Returning false from most events cancels the default action.
So if the current length is already 50 (or more), the handler returns false,
the KeyPress action is cancelled, and the character is not added.
   
   One fly in the ointment is the possibility of pasting into a TEXTAREA,
which does not cause the KeyPress event to fire, circumventing this check.
Internet Explorer 5+ contains an onPaste event whose handler can contain the
check. However, note that you must also take into account how many
characters are waiting in the clipboard to know if the total is going to
take you over the limit or not. Fortunately, IE also contains a clipboard
object from the window object.[1] Thus:
   
    <textarea onKeyPress="return ( this.value.length < 50 );"
onPaste="return (( this.value.length +
window.clipboardData.getData('Text').length) < 50 );"></textarea>
    
    Again, the onPaste event and clipboardData object are IE 5+ only. For a
cross-browser solution, you will just have to use an OnChange or OnBlur
handler to check the length, and handle it however you want (truncate the
value silently, notify the user, etc.). Unfortunately, this doesn't catch
the error as it's happening, only when the user attempts to leave the field,
which is not quite as friendly.
   
   Parts of this tip are courtesy of Hershel Robinson and James Aylard.
   
   [1]
http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/ref
erence/objects/clipboarddata.asp

</tip>

This message may contain information which is private, privileged or
confidential and is intended solely for the use of the individual or entity
named in the message. If you are not the intended recipient of this message,
please notify the sender thereof and destroy / delete the message. Neither
the sender nor Sappi Limited (including its subsidiaries and associated
companies) shall incur any liability resulting directly or indirectly from
accessing any of the attached files which may contain a virus or the like. 


More information about the thelist mailing list