Count the number of characters in a textbox


Introduction:

In web application, we need to count the character in the textbox for the validation purpose. Here we will see how to implement the same in JavaScript.

Initially we need to know about some attributes in the textbox, which are as follows,
  • onkeypress
  • onkeyup
  • onkeydown
  • onPaste
So here we raise the attribute event in textbox and implement as shown below in .aspx ,

<asp:textbox id="txtValue" runat="server" onkeypress="return CheckLength(this,150)" onkeyup="return CheckLength(this,150)" onkeydown="return CheckLength(this,150)" onPaste="return CheckLength(this,150)"></asp:textbox>

Here we are passing two parameters to the function CheckLength(this,150), "this" represents the object of the textbox and next parameter defines the maximum length allowed in the textbox. So we are calling the same function for all the attributes and find the number of the character in the textbox.

Finally we generate the function and add functionality as per our scenario using JavaScript. 

[ Javascript code ] 

function CheckLength(txt, maxLen) {
    try {
        if (txt != null) {
            var iLength = txt.value.length
            if (iLength <= maxLen) //Check the Limit.
            {
                //Display the remaining characters
                document.getElementById('<displayControlid>').innerHTML = maxLen - iLength + " are remaining characters.";
            }
            else {
                txt.value = txt.value.substring(0, maxLen);
                return false;
            }
        }
    }
    catch (e) {
        return false;
    }
}

Conclusion:

Through this article we can customize the code based on the requirements easily and count the character in the textbox. So we can split or avoid any kind of character at the time of the counting the characters.

Up Next
    Ebook Download
    View all
    Learn
    View all