Journeys in Javascript and the DOM: textarea max length
Posted by Dan Eastwell
This article describes how to create a textarea max length indicator that keeps a countdown of the number of characters you have left to type. It also stops input after the maximum number of characters has been reached. It will truncate characters after the maximum limit via copy and paste, either from the right-click dialogue, or from the browser menu.
The actual amount of active code in this example is minimal, the vast amount of code in this example is spent traversing the DOM to find the elements required, and a such, there's no javascript event handlers in the code. There is some required HTML, from which the javascript recognises the sections that need updating, and, 'controversially', pulls the values it needs.
There is a certain amount of repetition in the DOM traversing, and I'd like to clean that up - if anyone has any pointers as to how I'd remove that redundancy, let me know.
The required HTML
<textarea id="short_desc" name="short_desc" rows="5" cols="60">
</textarea>
<p class="note maxLength">Maximum
<span class="maxlength">100</span>
characters</p>
That's it!
The key parts that are searched for by the javascript are the textarea itself, and the classes maxLength and maxlength are used to denote the 'maximum characters' feedback paragraph and the maximum number of characters, which is held within the span. The note class for the paragraph I've used to style this type of paragraph - it's not necessary, but is added to the feedback paragraph when it's changed (if you were to copy this code, you could remove that from the script).
Accessibility
I'd like to think that this script is accessible, in that without javascript, the maximum number of characters is still present in the document, and the form works. The only missing functionality is not core to the form's functioning. My only question would be the accessibility or otherwise of the onKeyup event handler: is that likely to cause problems? This W3C WCAG document suggests that two event handlers should be specified.
The script
This is the textarea max length page, with the script found here.
There is also a language file, containing the error messages. This means you don't need to search through the script file, should you need to customise or translate these.
The script itself runs as follows:
- It first checks for DOM compatibility
- Then it searches for all the textareas in the document and puts these in a node collection
- It then cycles through these seeing if any textarea has a sibling element: these would be the notes containing the maximum length figure for the textarea
- If any of these siblings children's class names is 'maxlength', two functions are assigned for two event handlers (onChange and onKeyup).
- Both event handlers' functions essentially start the same way: they cycle through siblings' children with the 'maxlength' class name, then find the value of the first child (the maximum length figure)
- The maximum length is then compared to either the current length, for the onKeyup event handler (the user is still typing), or the total length, for the onChange event (the user has changed some of the data in the form, probably by a paste), then a message is returned to the user
I'll take that complicated set of instructions and break them down. Firstly, 1) check for DOM compatibility:
This needs to be completed in order to stop problems in browsers that don't support the DOM. It's done by checking whether or not document.getElementById actually means anything, i.e. returns true: if (!document.getElementById) return false;
.
Second on the list: search for all textareas and put these in a node collection. Simply done by: var formTextareas = document.getElementsByTagName("textarea");.
Cycle through, seeing if any has a sibling. This is done thusly:
for (var i=0; i < formTextareas.length; i++) {
var siblings = formTextareas[i].nextSibling;
while (siblings) {
for( var x = 0; siblings.childNodes[x]; x++ ){
...
}
siblings = siblings.nextSibling;
}
}
The main 'doing' part of the code happens where that ellipsis (...) is.
Next, If any of these siblings children's class names is 'maxlength', two functions are assigned. The two functions are in for the various ways the information in the textarea might change - e.g. by typing or by a cut and paste. The onChange event is basically a last resort, to check that not too much information is being added to the textarea, and there's no special DOM manipulation to get the message back, it just raises the alert.
if (siblings.childNodes[x].className=="maxlength"){
formTextareas[i].onchange = function(){
...
}
formTextareas[i].onkeyup = function(){
...
}
}
The searching for siblings and childnodes is a little bizarre - it's really my first foray into walking the DOM and seems a little excessive: I'll admit the code repetition is probably my lookout. The sibling/child relationship is as follows:
<textarea id="short_desc" name="short_desc" rows="5" cols="60"></textarea> (Sibling)
<p class="note maxLength"> (Sibling)
Maximum (Child) <span class="maxlength"> (Child)
100 (Child's child) </span> (Child) characters (Child)
</p> (Sibling closing tag)
The textarea and p tag are siblings, the text in the p tag and the span tag are its children. The maximum length text ('100') is the span tag's child.
The process of looking for the span with the class of 'maxlength' is this step: find siblings' children with the 'maxlength' class name, find the value of the first child. This is described above - the value of the first child of the element with the maxlength class name is the maximum length in characters we're looking for. This is the code in both event handlers' functions:
var siblings2 = this.nextSibling;
while (siblings2) {
for( var j = 0; siblings2.childNodes[j]; j++ ){
if (siblings2.childNodes[j].className=="maxlength") {
maxKeys = siblings2.childNodes[j].firstChild.nodeValue;
}
}
siblings2 = siblings2.nextSibling;
}
The final step in the code is the actual evaluation of what's being typed, or what's been pasted in.
When the user steps out of the textarea, after it's changed, which would be the onChange event after a pasting, then this is the code that does the work:
var theInput = new String(this.value);
if(theInput.length > maxKeys){
alert(keysLimtString + maxKeys + keysLimitEnd);
this.value = this.value.substring(0,maxKeys);
startstr = startstr;
endstr = endstr;
swapPTag(this,maxKeys,startstr,endstr,0);
}
A new String object is created to hold the value of what's inside the textarea. This is compared to the maximum number of characters that's just been found and if it's greater, the user is alerted, using the values from the language file, and the textarea's contents are set to a truncated length.
The final lines use the custom swapPTag function to put the original max length message back on the screen.
The second version of this code evaluates whilst you type - after a keyup event:
var str = new String(this.value);
var remaining = maxKeys - str.length;
if(remaining <= 0){
this.value = this.value.substring(0,maxKeys);
}
var endstr = remaining + textareaMaxCharsMsg;
if (remaining < 0){
endstr = textareaLimitMsg + maxKeys + textareaLimitEnd;
}
swapPTag(this,maxKeys,'',endstr,1);
This final piece of code does most of the actual non-DOM-traversing work of the script. It again creates a new String object and works out how many characters remain. If there aren't any left, it truncates the value that remains in the textarea (this.value = this.value.substring(0,maxKeys); ).
If there are characters left, it sets the message to be swapped in the document to the appropriate message, if not the end of the message shows that the limit has been reached. In both cases, the custom function, swapPTag is used to swap the note on the page to show the appropriate message.

<Infect you have also not applied max length property into your message box dffssdffssdffsffssdffssdffssdffssdffssdffssdffss [… Ed: Mahesh continues in this vein for some time… ] ffssdffssdffssdffssdffssdffssdffssdffssdffssdffssdffssdffss
Thanks Mahesh for your considered opinion.
By writing this article, I’m not saying that limiting character counts via javascript is necessarily usability or security best practice for every textarea.
In fact there are many situations where you may want to allow people to write as much as they like, for example where people are allowed to comments on blogs.
how to fix maxminm length & maximum rows using javascript
Thanks for the comment Ansari.
How do you mean maximum length? This does set the maximum length in characters.
Maximum rows is more difficult: you would need to calculate the width of your text. If the width is set using CSS in ems, then you know how many characters per row, given you are using courier for the font in the textarea (as courier is monospace, i.e. each character is the same width, 1em.)
You can then use the same method as above, dividing the maximum number of characters by the width to get the number of rows, or better, using a modulus operator (%), or math.floor() to avoid rounding.
I’ve not tested this, so let me know how you get on.
suppose i have one jsp page in which textfield is there. and i dont want repitetion of characters more than 5 times in my textfield, either it will be continous or discontinous, plz help me out, my id is :
jagjeet.be.cs@gmail.com
Sorry Jeet, I’m not a jsp programmer, I’m afraid. You’d probably need some form of regular expression to check for repeated patterns.
Try this tutorial:
http://www.regular-expressions.info/
Good luck!
thanks for reply dear, i went to that url which you have given me, but i didnt get any help from also, i know that i need to do this validation using regular expression but i m not getting how.
hi dan, i got that validation buddy, thanks for your help.
Great stuff, good to hear. If you did find a solution, could you leave it here? It might be useful for other people who have the same problem in the future.
Nice!! So easy to install too ;D I’m using it for a 160char SMS form, and it works GREAT!!
Thank you bow
That’s good to know Luggruff, thanks for the feedback.
Thanks Dan! Good stuff.
hi dan can u please mail me the entire html file containing the css and javascript
Hi Vikash
This is the textarea max length page, with the script found here.
Great script, very useful. Thank you!
Interesting. I’ll be using this in a few projects.
There seems to be a bug;
replace formname with form name replace formfield with form field
Now the textarea wont count.
If there is a fix it may be in the js files otherwise haven’t found it yet.
Cheers
This was cut off;
body onLoad=”document.formname.formfield.focus();”
Cheers