Friday, 6 January 2012

Count Characters Using JavaScript

A simple JavaScript function is presented here which can be used to count the number of characters typed in a text area. The numbers of characters can be displayed as it is typed and various actions can be taken according to the count on the fly.

Syntax


count(x);


Where 'x' is the reference to the text area. To execute this function after every key press, the following code should be added in the attributes of <textarea>.


onkeyup="count(this.value)"


Example


The function count(x) given in the code below does the following operations:

  • If count is less than 10, the count will be displayed in Yellow
  • If count is between 10 and 20, it will be displayed in Green
  • If count is greater than 20, it will be displayed in Red















Code


The complete code (HTML along with JavaScript) is given below. To see it in action, copy it to a text editor and save it with a file extension '.html'. Then open it using any browser.



<html>
<head>
<title>Count Characters In TextArea Using JavaScript</title>
<script type="text/javascript">
function count(x)

  var len = x.length;
  var count = document.getElementById("count");
  if(len<10)
    count.style.color = "#FFFF00";
  else if(len<20)
    count.style.color = "#00FF00";
  else
    count.style.color = "#FF0000";
  count.innerHTML = x.length;
}
</script>
</head>


<body>
<textarea cols="50" rows="5" onkeyup="count(this.value)">
</textarea>
<div id="count"></div>
</body>
</html>

No comments:

Post a Comment