Friday, 17 February 2012

JavaScript: live character count


In many situation, we offer the user the possibility of filling in a form and specifically a textarea. In those cases, we might decide to limit the number of characters and thus show the user how many remaining letters are available, with some sort of live character count.
It is possible to show the countdown using a JavaScript function called on key up. Let's see how we can do it.

We build the text area inside a form. In our example the calling of the function is placed in the form itself, but it possible to use it directly inside the textarea (if you prefer):
<form onkeyup="count();">

    <input type="text" id="message" size="40" maxlength="40">
    <br />
    Character count: <span id="characterCount">40</span>

The textarea has a max length of 40 characters, and so we start our character countdown from that value. The span tag with a specific id (characterCount) will initially show a starting value of 40, and then the function count() will change that value on the key up event.

The function
The JavaScript function is simple and should be placed in the head of your page:
<script type="text/javascript">
function count(){
    var characterCount = document.getElementById("message").value.length;
    document.getElementById("characterCount").innerHTML = 40-characterCount;
It basically inspects the length of our textarea which has an id="message". Then it changes the value inside the span with a value equal to 40 (our max length) minus the length of the textarea.
Every time a new letter is inserted in the textarea the span value decreases by one, starting from 40.
We can obviously change the max length according to our need.

And that's all for today.

1 comment:

  1. Hi, thanks so much for the script, is there any way to use it twice in a form? I was trying to add the script for a max of characters in the title and a max of characters in the body, but it didn't work.

    Thanks again.


Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.