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. if (document.getElementById('<%= txtComments.ClientID %>'))
  6. {
  7. var ctrl = document.getElementById('<%= txtComments.ClientID %>');
  8. var len = document.getElementById('<%= txtComments.ClientID %>').value.length;
  9. if (len <= maxSize) {
  10. var diff = parseInt(maxSize) - parseInt(len);
  11. if (document.getElementById('<%= txtRemain.ClientID %>'))
  12. {
  13. document.getElementById('<%= txtRemain.ClientID %>').value = diff;
  14. }
  15. }
  16. else
  17. {
  18. ctrl.value = ctrl.value.substring(0, maxSize);
  19. }
  20. }
  21. return false;
  22. }
  23. </script>
Screenshot:
txtRemain.jpg