Search code examples
javascriptjquerylivevalidation

Check length of field as user types


I have seen this ability over the web and I wasn't quite sure how to search for it, a good example is sending a text message it will say as you are typing:

132/160 - and the 132 counter will increase until you hit your limit.

My question was is it possible to get working with javascript alone, no jQuery library? However if I have to use jQuery I will, perhaps a point to a good tutorial, or maybe it's simpler than that, or even some terms to search for it, Thanks.


Solution

  • <!--This is your input box. onkeyup, call checkLen(...) -->
    <input type="text" id="myText" maxlength="200" onkeyup="checkLen(this.value)">
    
    <!--This is where the counter appears -->
    <div id="counterDisplay">0 of 200</div>
    
    
    <!--Javascript Code to count text length, and update the counter-->
    <script type="text/javascript"><!--
        function checkLen(val){
            document.getElementById('counterDisplay').innerHTML = val.length + ' of 200';
        }
    //--></script>