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>

Text box allow only Alphabets

Introduction 
Here I will show how to use Javascript to allow only alphabets in textbox or how to make textbox to allow only alphabets using javascript
 
 
<html>
<div>
               <script type="text/javascript">
                   function IsAlpha(e) {
                      // alert(e.keyCode);
                       var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;

//65 to 90 is Capital letter : 97 to 122 is small letter : 32 is Space  : Delete 127
                       var ret = ( (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <=

           122) || (keyCode == 32) || (keyCode == 08) || (keyCode == 127));
                      // document.getElementById("error").style.display = ret ? "none" : "inline";
                       return ret;
                   }
        </script>
            <input type="text" id="text1" onkeypress="return IsAlpha(event);" ondrop="return false;"
        onpaste="return false;" />

   
        </div>
</html>