Wednesday, July 24, 2013

Count and limit characters with Javascript

I recently had to limit the length of a text area to 250 characters so I first created the script below:

<script type="text/javascript">
            var count = 250;
            function limiter() {
                var tex = document.MyForm.MyField.value;
                var len = tex.length;
                if (len > count) {
                    tex = tex.substring(0, count);
                    document.MyForm.MyField.value = tex;
                    return false;
                }
                document.MyForm.CharsLeft.value = count - len; //display the chars left
                
            } 
</script>

After that I added the function to the onKeyUp event of the Text area. However I noticed that the count was incorrect. First of all it counted incorrectly and second, if you kept the button pressed it did not show on the page the correct number of chars left.

To fix this I also added the function to the onKeyDown event of the Text area. After that, everything was ok.


<td colspan="2">@Html.TextAreaFor(model => model.MyField, 4, 130,
                         new
                         {
                             onChange = "document.MyForm.MyField.value=this.value;",
                             onKeyDown = "limiter()",
                             TextMode = "MultiLine",
                             onKeyUp = "limiter()",
                             MaxLength = "250",
                             MaxChars = "250",
                             Rows = "2",
                             Cols = "125"
                          })
 </td>