Field character limiter





6
Date Submitted Thu. Oct. 26th, 2006 6:59 PM
Revision 1 of 1
Helper brendo
Tags forms | JavaScript | message | textarea
Comments 3 comments
This snippet also you to limit the input in a form field to a specified number of characters. It displays a counter so users can see how many characters they have left, and once they reach the limit the field just trims the length to your limit.

The following is a snippet from what I used when I implemented a tagboard to my site. Further revisions could/should read the LIMIT from the maxlength attribute

<form id="tagboard" action="url/here/" method="post">
    <fieldset>
        <legend>Tagboard</legend>
        <label for='name'>Name:</label>
            <input type="text" id="name" name='name' />
        <label for='message'>Message: </label>
            <span id='charleft'></span>
            <textarea id='message' name='message' onkeyup='go()' onkeydown='go()' rows='' cols=''></textarea>                           
        <input id='tag-submit' type="submit" name="submit" value="Tag IT!" />
    </fieldset>
</form>
 

function go()
{
    // Number of characters
    var LIMIT = 50;
    // Get the elements to fiddle with
    var textarea = document.getElementById('message');
    var span = document.getElementById('charleft');

    // if the textarea has less letters then the
    // limit, update span with the number of characters
    if (textarea.value.length <= LIMIT)
    {
        var newspan = parseInt(LIMIT) - parseInt(textarea.value.length);
        span.innerHTML = newspan;
    }
    // if the textarea has more, trim down to LIMIT
    else
    {
        textarea.value = textarea.value.substring(0, LIMIT);
    }
}
 

Brendan A

www.bloodbone.ws

Comments

Comments onkeyup
Sat. Oct. 28th, 2006 3:42 PM    Scripter SCoon
  Comments ah.
Sat. Oct. 28th, 2006 8:28 PM    Helper brendo
Comments Warning
Mon. Oct. 30th, 2006 7:20 AM    Beginner SurfMan

Voting