FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

JavaScript Character Counter for Text Areas

on in JavaScript DOM
Last modified on

A while ago, I had to implement a character counter for a business listing directory. The description field was supposed to hold about 400 characters. More than that would look like spam.

Here’s the solution I have come up with. Note that the HTML is minimal and is only relevant for these examples.

1. Feedback message

First, here is the JavaScript being executed on each keyup event:

<script>
function txtshow(txt2show) {
    document.getElementById('txtmsg').innerHTML = txt2show;
}

function keyup(what) {
    const maxKeys = 50;
    let str = new String(what.value);
    let len = str.length;
    let showstr = ${len} characters of ${maxKeys} recommended`;
    if (len > maxKeys) {
        showstr += '<br>Some information will be lost, please revise your entry';
    }

    txtshow(showstr);
}
</script>

Next, here is the form HTML with the textarea and the feedback container:

<form>
      <textarea cols="40" rows="5" onkeyup="keyup(this);"></textarea>
</form>

<div id="txtmsg">0 characters of 50 recommended</div>

2. Simple message

This example will show a simple message on each textarea blur event:

<script>
function textCounter(textarea, counterID, maxLen) {
    const cnt = document.getElementById(counterID);
    if (textarea.value.length > maxLen) {
        textarea.value = textarea.value.substring(0, maxLen);
    }
    cnt.innerHTML = maxLen - textarea.value.length;
}
</script>

And the form HTML with the textarea:

<form>
    <textarea name="text_area" cols="50" rows="5" onkeyup="textCounter(this, 'count_display', 3500);" onblur="textCounter(this, 'count_display', 3500);"></textarea>
</form>

And the message:

<span id="count_display">3500</span> characters remaining.

3. Multiple text areas

And finally, here’s an example for multiple textarea elements on a single page:

<script>
function textCounter(field, cntField, maxLimit) {
    if (field.value.length > maxLimit) {
        field.value = field.value.substring(0, maxLimit);
    } else {
        cntField.value = maxLimit - field.value.length;
    }
}
</script>

And the form:

<form name="myForm">
    <textarea name="message1" cols="28" rows="5" onkeydown="textCounter(document.myForm.message1, document.myForm.remLen1, 125);" onkeyup="textCounter(document.myForm.message1, document.myForm.remLen1, 125);"></textarea>
    <br>
    <input readonly type="text" name="remLen1" size="3" maxlength="3" value="125"> characters left
    <br>
    <textarea name="message2" cols="28" rows="5" onkeydown="textCounter(document.myForm.message2, document.myForm.remLen2, 125);" onkeyup="textCounter(document.myForm.message2, document.myForm.remLen2, 125);"></textarea>
    <br>
    <input readonly type="text" name="remLen2" size="3" maxlength="3" value="125"> characters left
</form>

That’s all!

Related posts