Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

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

You are here: irt.org | FAQ | JavaScript | Form | 11 | Q1105 [ previous next ]

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?'

©2018 Martin Webb