Count characters in a textarea using javascript



In this article I am going to explain the code for counting and displaying the number of characters in a textbox or textarea using javascript.


My requirement is to  count the characters in a textbox at runtime and restrict the number of characters. For that first i am creating a textbox.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        <font size="1" face="arial, helvetica, sans-serif">Only 50 characters allowed!
            <input id="text" type="text" size="40" onkeydown="CountLeft(this.form.text,this.form.left,50);"
            <input readonly type="lab" id="left" size="3" maxlength="3" value="50">
            characters left</font>

In the above code i have created a html textbox and a label. While entering text in textbox the label show the number of characters. For counting the no of characters i have a javascript function "CountLeft" which is called on  onkeydown and  onkeyup events because we have to count the no of characters while entering the characters in the textbox and also while erasing the characters. Below is the javascript code.

<script type="text/javascript">
    function CountLeft(field, count, max) {
        // if the length of the string in the input field is greater than the max value, trim it
        if (field.value.length > max)
            field.value = field.value.substring(0, max);
        // calculate the remaining characters
            count.value = max - field.value.length;

Thus the above javascript function counts the number of characters in the textarea on both the onkeydown and onkeyup  events. And if the count goes above 50 then it will restrict the characters.


Post a Comment

Online Casino