Count characters in text area using javascript

1 min


Today i will explain you how we can count the remaining characters in text area. This is the same as we see in old twitter.
First i show u by pictures how this looks like:-

Remaining characters
Remaining characters

When the remaining characters becomes 0 or negative then it shows in red color.

Remaining characters become negative
Remaining characters become negative

The code of the file looks like this:-


<title>Count characters in text area</title>
<script type="text/javascript">
function count(){
var current = 0;
var max = 40;
current = parseInt(document.getElementById("text").value.length);
var result = max - current;
if(result > 0)
document.getElementById("show").innerHTML = result;
document.getElementById("show").innerHTML = "<font color='red'>"+
<textarea id="text" cols="20" rows="5" 
onKeyDown="count()" onKeyUp="count()">
Remaining character: <b id="show">40</b>

I have used parseInt to convert the text to integer. document.getElementById(“text”).value.length is used the count the numbers of characters typed by the user in text area. document.getElementById(“show”).innerHTML is for inserting text in b tag. I have written my javascript code in the function name count.
So i am calling count function on onkeydown and onkeyup so that when the user enters a character the function will be called.
I have also used if and else to change the color of remaining characters. If the remaining characters or variable result is greater than 0 then ok if it is equal to zero or negative then i changed the font to red.
You can download the source code from here

Like it? Share with your friends!

Junaid Rehman

I am a blogger and freelance web developer by profession. I love to blog and learn new things about programming and IT World.