Check length of field as user types

Use the oninput event, where supported (all modern browsers, IE 9 and later) and onpropertychange for older Internet Explorers:

var myInput = document.getElementById("myInput");
if ("onpropertychange" in myInput && !("oninput" in myInput)) {
    myInput.onpropertychange = function () { 
        if (event.propertyName == "value")
            inputChanged.call(this, event);
    }
}
else
    myInput.oninput = inputChanged;

function inputChanged () {
    // Check the length here, e.g. this.value.length
}

onkeyup is not a suitable event for handling input, as there is a notable delay between the user entering text and your code noticing the change. A user could even hold the key down (for repeating text on Windows devices), but your code would not handle it.


<!--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>