Count characters in text area using javascript

1 min


2 shares

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:-

 

<!DOCTYPE HTML>
<html>
<head>
<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;
else{
document.getElementById("show").innerHTML = "<font color='red'>"+
result+"</font>";	
}
}
</script>
</head>
<textarea id="text" cols="20" rows="5" 
onKeyDown="count()" onKeyUp="count()">
</textarea>
Remaining character: <b id="show">40</b>
</body>
</html> 

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!

2 shares
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.