Try the following code for instance:
working code in jsfiddle.net
For textArea, use this:
<textarea id="txtBox"></textarea>
...
...
For textBox, use this:
<input type="text" id="txtBox"/>
<br>
<input type="text" id="counterBox"/>
<script>
var txtBoxRef = document.querySelector("#txtBox");
var counterRef = document.querySelector("#counterBox");
txtBoxRef.addEventListener("keydown",function(){
var remLength = 0;
remLength = 160 - parseInt(txtBoxRef.value.length);
if(remLength < 0)
{
txtBoxRef.value = txtBoxRef.value.substring(0, 160);
return false;
}
counterRef.value = remLength + " characters remaining...";
},true);
</script>
Hope this Helps!