Character counter in JavaScript
July 30, 2011 7 Comments
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:
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.