Textarea text counter / limiter

August 29, 2006 | Uncategorized | 7 Comments

I wrote a little prototype class for limiting the number of characters in a <textarea>. It also includes a counter if you want. You set the ID of the <textarea>, the ID of the <input> where the number of characters will be reported, and the number of characters. There is also an internal flag for whether or not to include carriage returns (\n or \r) in the count. Here's how to instantiate it:

<textarea id="textarea1" rows="5" cols="57"></textarea>
<br />
<input type="text" id="remaining" size="9" /> characters remaining
<script type="text/javascript">
var t1 = new TextCounter('textarea1', 'remaining', 150);
</script>

And here's the full script:

var TextCounter = Class.create();
TextCounter.prototype = {
    initialize: function(textareaid, inputid, maxLength) {
        this.maxLength = maxLength;
        this.textarea = $(textareaid);
        this.input = $(inputid);
        this.input.value = maxLength;
        this.input.readonly = true;
        this.input.disabled = true;
        Event.observe(this.textarea, 'keyup', this.checkChars.bindAsEventListener(this));
        Event.observe(this.textarea, 'keydown', this.checkChars.bindAsEventListener(this));
        this.checkChars();
    }, 
    checkChars: function(e) {
        var includeBreaksInCount = false; // false = don't count a return (\r or \n) in the count.
        var charCount = this.textarea.value.length;
        var breaks = 0;
        if (!includeBreaksInCount) {
            var lines = this.textarea.value.split('\n');
            breaks = lines.length;
            // check for /r at the end of the lines (IE)
            for (var i=0; i<lines.length; i++) {
                var line = lines[ i ];                
                if (line.charCodeAt(line.length-1) == 13)
                    breaks++;
            }
            
        }
        
        // check if over limit
        if ((charCount-breaks) > this.maxLength) {            
            this.textarea.value = this.textarea.value.substring(0, (this.maxLength + breaks) );
        }
        
        // update counter
        if (this.input) {
            if ((charCount-breaks) > this.maxLength) {
                this.input.value = 0;
            } else {
                this.input.value = (this.maxLength + breaks) - charCount;
            }        
        }
    }
}

7 responses to “Textarea text counter / limiter”

  1. Eddie H says:

    I am using a php form creator application. It does not allow for custom HTML for the input fields. So I cannot add an ID to each field. However, it does put a paf="inputsid", so could I use this paf field to identify the input field for limiting the text. I would like to limit the text on the Male Description field and Female Description field. Please get back to me at <img src="http://edswebdesign.com/emailimage.jpg"&gt;

  2. Liz J says:

    Hi,
    I’m new at Javascript and have been looking for a way to limit double byte characters (such as Kanji) in a textarea in IE. Do you know a way to do that? At first, this script looks like it works for double byte, but if you keep typing after it reaches 0 (which someone may do if they’re not looking at the screen), it will then delete most of what you’ve entered instead of only deleting the excess number of characters. Any help would be greatly appreciated.

  3. John Dyer says:

    @Liz, I’m sorry, but I currently don’t have any experience with doing this on double byte languages. If you come up with something I’d love to hear it.

  4. roshan sherstha says:

    nice site and concept , but the bold , italic in the comment area doesn’t work

  5. macguru says:

    Nice Example, there is one big bug though. When you turn on count line breaks in Opera or Internet Explorer each line break is counted as two characters :(

    Still nicely coded class.

  6. I’m not that much of a online reader to be honest but your sites really nice,
    keep it up! I’ll go ahead and bookmark your site to come back down the road.
    Cheers

Leave a Reply

Hi, I'm John Dyer. In my day job, I build websites and create online seminary software for a seminary in Dallas. I also like to release open source tools including a pretty popular HTML5 video player and build tools that help people find best bible commentaries and do bible study. And just for fun, I also wrote a book on the theology of technology and media.

Fork me on GitHub

Social Widgets powered by AB-WebLog.com.