Character counter in JavaScript

This is about creating a character counter for textarea and limit it accordingly. You may have seen this kinda stuff in some messaging site mostly in sites which provides SMS facilities. They limit us to enter only specified number of characters in text area. Also in some sites there are limitation on characters in comments. So this article will help you in building a similar thing which will look like below picture:

Character counter for text area in JavaScript

Step 1 create a text area for entering text and an input text box which will hold remaining character count.

     Character Remaining:
     <INPUT  disabled size="3" value="140" name="txtLen" id="txtLen">
     <TEXTAREA id="textArea" name="textArea" rows="7" value="" cols="50"></TEXTAREA>

Step 2 Add key events on text area to monitor character count in it:

<TEXTAREA id="textArea" onKeyDown="countChars()" onKeyUp="countChars()" name="textArea" rows="7" value="" cols="50"></TEXTAREA>

Step 3 Create JavaScript function to calculate length of text entered in text area and change input box’s value accordingly and if length goes beyond limit then substring text up to length limit:

function countChars() {
     var l = "140";
     var str = document.getElementById("textArea").value;
     var len = str.length;
     if(len <= l) {
     } else {
          document.getElementById("textArea").value=str.substr(0, 140);

Step 4 Apply some CSS to it:

   FONT-WEIGHT: bold;
   BACKGROUND: #000000;
   MARGIN-LEFT: 0px;
   PADDING-TOP: 5px;
   FONT-WEIGHT: bold;
   FONT-SIZE: 12px;
   COLOR: #000;
   FONT-FAMILY: Tahoma;
   FONT-WEIGHT: bolder;

And its done. Hope this helps you.

7 thoughts on “Character counter in JavaScript

  1. Pingback: JavaPins

Leave a Reply to hayden Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.