Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1105 How do I count the number of characters entered within a textarea?

irt.org | Knowledge Base | JavaScript | Form 11 | Q1105 [ previous next ]

Q1105 How do I count the number of characters entered within a textarea?

If you mean "How do I stop the user from entering more than x number of chars in a textarea" The answer is "It is not easy"

Internet Explorer 4 and Netscape Navigator 4 can capture keystrokes but have problems if the user presses backspace or so...

I would try this - the onKeyUp counts the strokes in v4 and the onChange does the dirty deed on v3:

<script language="JavaScript"><!--
maxKeys = 100;
keysSoFar = 0;
alerted = false;

function change(what) {
    if (!alerted) alert('Keep it short, please');
    what.value = what.value.substring(0,maxKeys-1); // chop after 100
    alerted = true;
}

function keyup(what) {
    keysSoFar++;
    if (keysSoFar > maxKeys) {
        if (!alerted) alert('That\'s enough!');
        what.value = what.value.substring(0,maxKeys-1); // chop the last typed char
        alerted = true;
    }
}
//--></script>

<form>
<textarea cols=100 rows=20 onChange="change(this)" onKeyUp="keyup(this)"></textarea>
</form>

Feedback on 'Q1105 How do I count the number of characters entered within a textarea?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.