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.

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

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) {
          document.getElementById("txtLen").value=l-len;
     } else {
          document.getElementById("textArea").value=str.substr(0, 140);
     }
}

Step 4 Apply some CSS to it:

DIV{
   PADDING-RIGHT: 5px;
   PADDING-LEFT: 5px;
   FONT-WEIGHT: bold;
   BACKGROUND: #000000;
   PADDING-BOTTOM: 5px;
   MARGIN-LEFT: 0px;
   PADDING-TOP: 5px;
   color:#FFFF00;
}
INPUT{
   BORDER:#000000;
   FONT-WEIGHT: bold;
   FONT-SIZE: 12px;
   COLOR: #000;
   FONT-FAMILY: Tahoma;
   BACKGROUND-COLOR: #FFFF00;
}
TEXTAREA{
   FONT-WEIGHT: bolder;
   BACKGROUND-COLOR: #DDCC00;
   WIDTH:100%;
}

And its done. Hope this helps you.

Advertisements

About harryjoy
A passionate self-taught software developer. Currently working as Lead Software Engineer in an IT company.

7 Responses to Character counter in JavaScript

  1. Pingback: Some useful JavaScript functions « harryjoy

  2. Pingback: JavaPins

  3. hayden says:

    you beauty!

  4. Ryan says:

    Works well. Thank you.

  5. costanzo88 says:

    easily understood and applied thank you

  6. milton says:

    You made it easy

  7. TG says:

    Thanx this is a very good code I like it…:-) and I bookmarked this page….

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: