Count the characters while entering in TextBox using Javascript

Count the characters while entering in TextBox using Javascript

 
It explains about the Count the characters while entering in TextBox using Javascript.
 
Design:
  1. <table cellpadding="0" cellspacing="0" border="0" width="100%">  
  2.      <tr>  
  3.           <td>  
  4.                <asp:TextBox ID="txtComments" BackColor="Gray" ForeColor="White" runat="server" TextMode="MultiLine" onkeyup="return CountCharacters();" Width="400px" Height="75px"></asp:TextBox>  
  5.           </td>  
  6.      </tr>  
  7.      <tr>  
  8.           <td style="padding-top:10px;">  
  9.                Characters remaining: <asp:TextBox ID="txtRemain" BackColor="Gray" ForeColor="White" runat="server" Text="200" Width="45px"></asp:TextBox>  
  10.           </td>  
  11.      </tr>  
  12. </table> 
JavaScript:
  1. <script type="text/javascript">  
  2. function CountCharacters()   
  3. {  
  4.      var maxSize = 200;  
  5.   
  6.      if (document.getElementById('<%= txtComments.ClientID %>'))   
  7.      {  
  8.           var ctrl = document.getElementById('<%= txtComments.ClientID %>');  
  9.           var len = document.getElementById('<%= txtComments.ClientID %>').value.length;  
  10.           if (len <= maxSize) {  
  11.                var diff = parseInt(maxSize) - parseInt(len);  
  12.   
  13.                if (document.getElementById('<%= txtRemain.ClientID %>'))   
  14.                {  
  15.                     document.getElementById('<%= txtRemain.ClientID %>').value = diff;  
  16.                }  
  17.           }   
  18.           else   
  19.           {  
  20.                ctrl.value = ctrl.value.substring(0, maxSize);  
  21.           }  
  22.      }  
  23.   
  24.      return false;  
  25. }  
  26. </script> 
Screenshot:
 
txtRemain.jpg