Monday 31 October 2011

Count Number Of Characters in a Textarea Using JavaScript

Ever wanted to create a cool textarea or a text box that counts the number of characters in it just as in Twitter or some other sites. It is much easier to built one for your own site than you might have expected. With a simple javascript function, you can count the number of characters as you type and display it.
If you have a basic understanding in HTML and JavaScript, you could make one in a couple of minutes.
Here is a simple version of the complete code along with the required HTML tags.

<html>
<head>
<title>Count</title>
<script type="text/javascript">
function count(x)
{
document.getElementById("cnt").innerHTML = x.value.length;
}
</script>
</head>
<body>
<textarea onkeyup="count(this)"></textarea>
<span id="cnt"></span>
</body>
</html>

Here the function count(x) is used to count the number of characters in the textarea and is displayed inside the span element. The count function is invoked every time a character is entered in the textarea.

You can  add more functionality by altering the count function.
For example, if you want to make a character count down the replace the count function with the following code.

function count(x)
{
document.getElementById("cnt").innerHTML = 200 - x.value.length;
}

This will create a count down beginning from 200.

If you want to make it more attractive by giving different colour for the numbers then use the following code.

function count(x)
{
var len = x.value.length;
if(len<100)
{
document.getElementById("cnt").innerHTML = "<span style=\"color:#00FF00\">"+len+"</span>";
}
else
{
document.getElementById("cnt").innerHTML = "<span style=\"color:#FF0000\">"+len+"</span>";
}
}

The above code will cause the number to be displayed in Green colour if the count is less than 100 and Red if it is greater.

Try yourself with more conditions and styling to suit your needs.

Happy Coding...! 

No comments:

Post a Comment