If you have a simple message board on your site or perhaps a form where users can submit a review, you might want to limit the amount of characters that the user enters into a textarea, presumably because you want to control the format of your page when the review is shown (you can’t have those nasty users spoiling the look of your website with 6000 word reviews now can you?!) .

Obviously, this isn’t going to stop the determined essayist as they can just disable javascript in their browser and type as many words as they like (that needs to be dealt with by a server side script) but for the sake of this code snippet, it adds a little ‘feature’ to your otherwise dull textarea.

Enough warbling from me, put this javascript inside the <head> tags of your document.

1
2
3
4
5
6
7
8
9
10
11
12
13
<script type="text/javascript">
var maxLength=250;
function charLimit(el) {
    if (el.value.length > maxLength) return false;
    return true;
}
function characterCount(el) {
    var charCount = document.getElementById('charCount');
    if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
    if (charCount) charCount.innerHTML = maxLength - el.value.length;
    return true;
}
</script>

And here’s the html:

1
2
3
4
<form>
    <textarea onKeyPress="return charLimit(this)" onKeyUp="return characterCount(this)"  rows="8" cols="40"></textarea>
</form>
<p><strong><span id="charCount">250</span></strong> more characters available.</p>

To change the amount of characters allowed, change these two lines:

1
2
var maxLength=250;
<span id="charCount">250</span>

Example


250 more characters available.

Similar Posts:

  2 Responses to “Textarea Character Count”

  1. Once the char count has been hit, backspace/Delete is no longer allowed.

  2. Ah, good spot Iain :)
    I needed to change this line

    function charLimit(el) {
        if (el.value.length == maxLength) return false;
        return true;
    }

    to this:

    function charLimit(el) {
        if (el.value.length > maxLength) return false;
        return true;
    }

    I’ve amended the code in the post.
    It should work fine now :)

 
© 2012 ElanManSuffusion theme by Sayontan Sinha

Page optimized by WP Minify WordPress Plugin