Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to count characters in a text box using JavaScript in ASP.NET

Author: Jeff Nava

In this article by using JavaScript, we will see how we can count characters and fix the length of characters in a text box control.

Most of the feedback or complaint and suggestion forms on different websites; we have seen that they restrict users to give their input not more than given number of characters. Many websites which restrict users also shows remaining characters or number of input characters. In this article, we will see how easily we can do this. So if you have this requirement, simply copy the JavaScript function and use it in your code or follow these steps.

 
  1. Open Visual Studio 2010
  2. File > New > Website
  3. Visual basic or Visual C# > ASP.NET Empty Web Site
  4. Website > Add New Item > Web Form
  5. Add following code in form tag

    <div>
            <table>
                <tr>
                    <td colspan="2">
                        <h3>Character Count in a text box</h3>
                    </td>
                </r>  
                <tr>
                    <td>
                        Write Text:
                    </td>
                    <td>
                        <asp:TextBox ID="txtCharacters" runat="server" Height="50px" Width="200px"
                        TextMode="MultiLine" onkeyup="CharacterCount()"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        Character Count:
                    </td>
                    <td>
                        <asp:Label ID="lblCharacterCount" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
        </div>
     
    You can see I have called a JavaScript function in the onkeyup event of Textbox. This function is defined below.
     
  6. Now add following JavaScript function

    <script language="javascript" type="text/javascript">
          function CharacterCount() {
              var txtCharacters = document.getElementById('txtCharacters');
              var chars = txtCharacters.value.length;
     
              document.getElementById('lblCharacterCount').innerHTML = chars;
           
              if (chars > 30) {
                  txtCharacters.value = txtCharacters.value.substring(0, 30);
              }
          }
    </script>

    I am simply getting length of characters in the Textbox and assign this value to Label control. Then I am checking if the character length is greater than 30 then I am setting the Textbox character limit to 30.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to fix GridView Header in ASP.NET Using jQuery

Disclaimer - Privacy
© 2002-2017 DevASP.net