Count characters in text area using javascript
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:- When the remaining characters becomes 0 or negative then it shows in red color. The code of the file looks like this:- [code lang=”javascript”] <!DOCTYPE HTML> <html> <head> <title>Count characters in text area</title> [...]
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:-
When the remaining characters becomes 0 or negative then it shows in red color.
The code of the file looks like this:-
[code lang=”javascript”]
<!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>[/code]
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
Share this article
Written by : 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.
Follow us
A quick overview of the topics covered in this article.
Latest articles
February 13, 2025
February 13, 2025
February 13, 2025
February 13, 2025
February 13, 2025