Limit Characters in a Textarea with Prototype


This entry is part 7 of 10 in the series Prototype Tutorial

Lately I have fallen in love with prototype and in effort to challenge myself and my skills I continue to brainstorm ways to use Prototype as often as possible.

Until I started using the Really Easy Validation library I hadn't done a lot with Prototype and forms. But after I did some custom work using that library I realized I also needed a text area with a character counter. That was easy enough, but I wanted to make it something that was nice and expandable, so I did.

We'll start with the HTML code I already had for the two text areas whose character's I want to count and limit.

HTML

  <div class="formrow">
    <label for="txtdesc">Description</label> <span>(<span id="counter-txtdesc"><b>#</b></span> characters)</span><br />
    <textarea name="txtdesc" id="txtdesc"></textarea>
  </div>

  <div class="formrow">
    <label for="comments">Comments</label><br />
    <textarea name="comments" id="comments"></textarea>
  </div>

I will change two lines in my .js file to initiate the character counting.

JavaScript

function init(){
    makeItCount('txtdesc', 300, false);
    makeItCount('comments',100);
}

I've defined that both text areas: txtdesc and comments are to have limits. The text area description will be limited to 300 characters and comments will be limited to 100 characters.

New 3rd, optional, parameter Added 4/16/08
The 3rd parameter allows you to override the limiting functionality. It defaults to true but can be overridden by passing false this will allow the text field to accept and not trim down the entry to the maximum amount, ti will continue to count up and inform you how over the limit you are so you can pick and choose what to trim down.

Is that more twitter like? I wouldn't know since I don't twitter(yet).


Since an element with the id 'counter-txtdesc' exists the script has a place to put the character count, in this case: 0/300.

No element with the id 'counter-comments' exists, so the script will create a div immediately below the text area with that id and puts 0/100 as the text within it.

When the count is below the maximum number of characters the relative counter- element also has the class of charcount-safe applied to it. When you meet or go over the character limit charcount-safe is removed and charcount-limit is applied. The script also trims down your content to the specified number of characters once you have gone over it.

If either text area doesn't exist the script does not return an error, it just disregards the assignment to count that area.

Pretty easy. There's additional customization I'd like to add to it but I need to research a few things before I do that!

Version 2

New update by request.

I've added a 3rd parameter (optional) to override the limiting functionality. Documentation above has been altered to allow for this change.

Demo & Download

You can view the demo to see this example live or download the script under the MIT License, same as Prototype and Scriptaculous.

Update 4/17/08
In response to a comment about an IE bug I looked into the problem...the problem was with the demo, not the script. I had used a meta tag <meta name="description" value="" /> and named the text area description. IE was picking up the <meta> tag instead of the <textarea> tag. Which I guess is just a friendly reminder that:

  • name is technically deprecated according to the w3c's XHTML 1 documentation
  • Just be unique - Just name and id elements uniquely, only duplicate the name and id within the same element to eliminate confusion, k?

Old versions

Series Navigation«Alternating Colors Using PrototypeZip Code, Phone Number and Replacing Empty Fields with Really Easy Validation»

Popularity: 76% [?]


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Trackbacks & Pingbacks

Prologue Theme Mod with 128 Chars Limit | Play Work Play Studio

[...] I am, the first thing I do is of course look around the net for scripts to do the functionality. And Terri Ann just so happen to create the very functionality a week ago. There are actually quite a lot of such scripts, but I liked Terri’s for its ease of use and [...]

Pingedback: 6 months ago

Reader Comments

Hi, Great article, I was looking for something like that for a while :).

I'm developing a web application for sending SMS messages, with this application you can send English messages (max characters per message is 160) but if you want to send a message with complicated characters (Chinese, Arabic, ... etc), the max number of characters becomes 70 !!! I'm wondering how can the script be modified to do this? When you type a letter in Chinese for example the limit changes instantly to 70 ! The problem is that I don't know Javascript I'm wondering whether hacking this script to do this is easy or not.

Thanks :)

I started looking around for way to limit the length of a text area and ran intot he same old bloated js routines and the site Im developping already uses prototype so when I saw your tutorial and demo I jumped for joy. nice use of prototype and character count lightweight and uber easy to implement

Bravissimo!

How could I go about disabling the max allowed characters so that a user can paste in larger content and then pare it down? the way that twitter.com does it is very nice

thanks, Phillip

hmmm it seems this doesnt work in IE6 or IE7 anyone found a way around it so it works in Internet exploder?

@Kinetic

In the demo I had a <meta name="description" /> tag which IE was recognizing instead of the <textarea name="description" id="description"></textarea>

Oops! My bad! This has been fixed and I've added a note in the blog about it!

Thanks everyone for your comments, keep suggestions and bugs coming. :)

@Phillip

I've posted a version two that allows for an over-ride 3rd parameter that allows you to enter more than the maximum amount of characters

Nice version 2. I did some digging around in twitter's code and found that they count characters this way:

HTML 140/140

Javascript: function postProcessUpdateKeypress(box, e) { var val = box.value; updateStatusTextCharCounter(val); } function updateStatusTextCharCounter(value) { $('status-field-char-counter').innerHTML = 140 - value.length; if (value.length > 130) { $('status-field-char-counter').setStyle({ color: 'red' }); } else if (value.length > 120) { $('status-field-char-counter').setStyle({ color: 'orange' }); } else { $('status-field-char-counter').setStyle({ color: 'black' }); } };

** Edited by admin 4-17-2008 @3:54pm to fix formatting

Terri, nice fix glad it was only a conflict with the standard meta tag description and renaming the textarea to txtdesc (or anything else for that matter as long as you edit the js file to reflect your text area name/id and as long as it isnt being called up in the head by a meta tag or other tag) sure does the trick again very nice, very slick and nice to know you are on top of it 5 out 5 wOOt

Hi Terri!

Thanks for a nice script. Is it possible to limit and

with this method? is yes, how?

Thanks in advance...

Marc

Ah crap, hadn't noticed that html tags was allowed here. They used to be forbidden with a big F! :P

Anyway , I wanted to know if you could limit other elements, like div, span and p with your script... and I've actually found a way to do it now with the prototype truncate string.

At the moment I'm just using:

Script: $('truncate').update($('truncate').innerHTML.truncate(10))

Content: </span

And it works.. but do you think it can be done in a smarter/faster way?

this guy does it in a very different way, but it doesn't work here :/

Anyway, take care :) Marc

Thanks for your code. Just a line to ask your help: if I (copy &) paste into the textarea the field is not updated. I searched around the net but I haven't find anything. The only solution that I came with is to use new

Form.Element.Observer($(id), 0.5, function(){charCounter(id, maxsize, limited);})

instead of the 2 Event.observe. Every 500ms it check if the textarea is changed and even if you copy&paste it updates the counter. Many thanks, P.

Hello! according to Phillips post I have updatet your script to output a message or to color the letters when a maximum limit of letters is reached.

function charCounter(id, maxlimit, limited){
    if (!$('counter-'+id)){
        $(id).insert({after: '<div id="counter-'+id+'"></div>'});
    }
    if($F(id).length >= maxlimit){
        if(limited){    $(id).value = $F(id).substring(0, maxlimit); }
        $('counter-'+id).addClassName('charcount-limit');
        $('counter-'+id).removeClassName('charcount-safe');
    } else {    
        $('counter-'+id).removeClassName('charcount-limit');
        $('counter-'+id).addClassName('charcount-safe');
    }
    $('counter-'+id).update( $F(id).length + ' von ' + maxlimit );
    // here is the updated Code START
    if ($F(id).length > 25) {
    // do here what ever you want if the limit is reached
    alert("Maximum letters are reached. ...");
    }
    // here is the updated Code END
}

Great script.

If you place the containing the remaining characters in the Label your approach will be more accessible to screen readers as they only speak labels when in forms mode.

i.e.

Description (0/300 characters)

Mark