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>