Character counter for textarea fields

Discussion in 'JavaScript' started by liam1412, Sep 24, 2008.

  1. #1
    Hi

    Does anyone know where I can get a character counter script for textarea fields. I have been looking all day but can't seem to find one.

    Thanks
     
    liam1412, Sep 24, 2008 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    in theory you should be able to do something like this via mootools:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-UK">
    
    <head profile="http://gmpg.org/xfn/11">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="robots" content="index,follow" />
    <meta http-equiv="Content-Language" content="en" />
    <meta name="author" content="webdemar" />
    <meta name="copyright" content="Copyright ? 2008 fragged.org, All Rights Reserved" />
    <meta name="revisit-after" content="7 Days" />
    <script type="text/javascript" src="mootools-core.js"></script>
    <title>mootools character count script</title>
    
    <style>
    body {
        font-family: Verdana, Arial, Helvetica, sans-serif;
        font-size: 11px
    }
    </style>
    </head>
    <body>
    <div id="commentInfo">Write a comment (used <span id='left'>0</span>/55 chars) <span id="warning"></span></div><br />
    <textarea data-maxchars="55" id="comment" cols="70" rows="5"></textarea> 
    
    <script type="text/javascript">
    window.addEvent("domready", function() {
        
        var textArea = $("comment");
        var maxChars = textArea.get("data-maxChars");
        
        // create a custom focused property so that we only capture keystrokes when it is
        textArea.addEvents({
            focus: function() {
                this.focused = true;
            },
            blur: function() {
                this.focused = false;
            }
        });
        
        // attach a key listener
        window.addEvent("keydown", function(e) {
            if (textArea.focused) {
                // should really compare e.key against alpha numerics and whatever allowed chars we have 
                // so it does not fire when they backspace or delete or use arrow keys to move
    
                // current count is...
                var chars = textArea.get("value").trim().length;
    
                // allowed?
                if (chars >= maxChars) {
                    // kill keyboard event...
                    // e.stop();
                    
                    // inform them its full!
                    $("warning").set("html", "<strong>limit reached!</strong>");
                    
                    // remove surplus chars
                    textArea.set("value", textArea.get("value").substring(0,maxChars));
                }
                else {
                    // reset warning field
                    $("warning").set("html", "");   
                }
                // inform how much left
                $("left").set("text", chars);
            }
        });
    });
    </script>
    </body>
    </html>
    HTML:
    view live demo here: _http://fragged.org/dev/textarea.php
    grab a copy of mootools framework from _http://mootools.net/download

    if you don't want to do that, you can always get the count like so:

    var charCount = document.getElementById("comment").value.length;

    good luck
     
    dimitar christoff, Sep 24, 2008 IP
    liam1412 likes this.
  3. liam1412

    liam1412 Active Member

    Messages:
    387
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Moo tools looks pretty funky. DO you just upload it to every site you use and link to it the normal way.

    <script type="text/javascript" src="js/mootools.js"></script>
     
    liam1412, Sep 24, 2008 IP
  4. liam1412

    liam1412 Active Member

    Messages:
    387
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #4
    Cheers Man. Works a treat!!!!!!

    Rep added.
     
    liam1412, Sep 24, 2008 IP
  5. liam1412

    liam1412 Active Member

    Messages:
    387
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #5
    Not to be cheeky but there is one tiny bug in it. As I know nothing of JS I can't find it.

    Basically it allows it to go 1 character over the limit.

    I know its a tiny thing but it looks a bit silly when it says 56 of 55 characters user. lol
     
    liam1412, Sep 24, 2008 IP
  6. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #6
    sure, my bad - event needs to be keyup not keydown. mootools is a framework that extends and makes javascript universal, object orientated and cross-browser compliant. it also provides shortcuts to a number of functions, the dom, animation effects etc etc. very handy to have - but there are also other strong frameworks like jquery, extjs, yui, gwt, prototype etc etc. i just use mootools myself =)

    the fix from script onwards:
    
    <script type="text/javascript">
    window.addEvent("domready", function() {
        
        var textArea = $("comment");
        var maxChars = textArea.get("data-maxChars");
        
        // create a custom focused property so that we only capture keystrokes when it is
        textArea.addEvents({
            focus: function() {
                this.focused = true;
            },
            blur: function() {
                this.focused = false;
            }
        });
        
        // attach a key listener
        window.addEvent("keyup", function(e) {
            if (textArea.focused) {
                // should really compare e.key against alpha numerics and whatever allowed chars we have 
                // so it does not fire when they backspace or delete or use arrow keys to move
    
                // current count is...
                var chars = textArea.get("value").trim().length;
    
                // allowed?
                if (chars+1 >= maxChars) {
                    // kill keyboard event?...
                    // e.stop();
                    
                    chars = maxChars;
                    
                    // inform them its full!
                    $("warning").set("html", "<strong>limit reached!</strong>");
                    
                    // remove surplus chars
                    textArea.set("value", textArea.get("value").substring(0,maxChars));
                }
                else {
                    // reset warning field
                    $("warning").set("html", "");   
                }
                // inform how much left
                $("left").set("text", chars);
            }
        });
    });
    </script>
    
    Code (markup):
     
    dimitar christoff, Sep 24, 2008 IP
  7. liam1412

    liam1412 Active Member

    Messages:
    387
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #7
    Nice one again.

    Thanks
     
    liam1412, Sep 24, 2008 IP