Count characters left on keypress using javascript

By bryan tugade

We can count how many characters left on keypress using javascript. Here's how.

<script type="text/javascript" language="javascript">
     function CountTxtLeft(StrTxt, txtCount, totaltxt) {
    if (StrTxt.value.length > totaltxt)
    {
        StrTxt.value = StrTxt.value.substring(0, totaltxt);
        }
    else
    {
        txtCount.value ='Total characters left :' + (totaltxt - StrTxt.value.length);
         }
}
</script>

Put the code above in the HEAD tags of your source code. Then call it in your text area to count how many characters left to input in your textarea control.

i.e.

<textarea id="message" runat="server"  cols="1"
             
onkeydown="howmanycharactersLeft(this.form.message,this.form.charleft,3000);" onkeyup="howmanycharactersLeft(this.form.message,this.form.charleft,3000);"
            
style="border: thin solid gray; width: 407px; height: 114px">  </textarea>
<input id="charleft" type="text" readonly="true"
        
style="border:none 0px transparent; width: 186px;" />


You can download the snippets here .

Count characters left on keypress using javascript  (684 Views)
Create New Account