Thursday 4 September 2014

Text Box Characters Counter using Javascript

In forms when using text boxes or text areas with limited character length (usually needed for forms that submit data to a database) it is always a good idea to tell the user how many characters they have remaining. This javascript snippet is especially useful for textarea fields since they can't be assigned a text limit in HTML but can be restricted using this code.
The following example shows how you can do this. This is a very simple and cute idea to help the user know exactly how many characters can be typed further. Do these small add-ons to your forms and they will look really professional.

 
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.5.js"></script>
    <script>
    function countChar(val) {
        var len = val.value.length;
        if (len >= 100) {
          val.value = val.value.substring(0, 100);
        } else {
          $('#charNum').text(100 - len);
        }
      };
    </script>
  </head>

  <body>
    <textarea id="field" onkeyup="countChar(this)" ondrop="countChar(this)" onfocus="countChar(this)" onload="countChar(this)"  ></textarea>
    <div id="charNum1">(Maximum characters:<span id="charNum" > 100</span>)</div>
  </body>

</html>