User Tools

Site Tools


notes:javascript:textarea_length_counter

Textarea Length Counter

This is one of the methods to show the current length of text entered into a textarea HTML element:

    var MAX_CHARS = 100; // the maximum number of characters allowed in the textarea
    var text, counter; // the textarea and the counter span element
 
    // onkeydown
    function CheckMessageLength()
    {
        var len = parseInt(text.value.length);
 
        if (len < MAX_CHARS)
        {
            event.returnValue = true;
        }
        else
        {
            // Check arrow keys, delete, and backspace.
            if ((event.keyCode >= 37 && event.keyCode <= 40) || (event.keyCode == 8) || (event.keyCode == 46))
                event.returnValue = true;
            else
                event.returnValue = false;
        }
    }
 
    // onkeyup
    function CountCharactersInMessage()
    {
        var len = parseInt(text.value.length);
 
        if (len > MAX_CHARS)
        {
            text.value = text.value.substring(0, MAX_CHARS);
            len = MAX_CHARS;
        }
 
        counter.innerText = MAX_CHARS - len; // revert the counter to show the number of remaining characters
    }
 
    function Init()
    {
        text = document.getElementById('text');
        counter = document.getElementById('counter');
 
        counter.innerText = MAX_CHARS - text.value.length;
    }

It updates the counter span element with the current length of text entered to a textarea element:

<form id="form1" runat="server">
    Enter text (max 100 characters):
    <br />
    <textarea id="text" rows="6" cols="30" 
        onkeydown="CheckMessageLength()"
        onkeyup="CountCharactersInMessage()"></textarea>
    <br />
    <span id="counter"></span> characters remain
</form>
 
<script lang="javascript" type="text/javascript">
    Init();
</script>

… and this is how it looks:

You can download the entire code from here.

notes/javascript/textarea_length_counter.txt · Last modified: 2020/08/26 (external edit)