te****@hotmail.com wrote on 07 mei 2008 in comp.lang.javascript
:
>
I have the below that limits the textarea input to 500 characters but
cant get the alert message to work. It doesnt show anything. Please
advise.
<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
alert("You are trying to enter more
than 500 characters");
beware of linebraks!!!
} else {
the else is not needed.
limitCount.value = limitNum - limitField.value.length;
}
}
</script>
-----------------------------------------------------------------------
---------
<form name="myform">
<textarea name="limitedtextarea"
onKeyDown="limitText(this.form.limitedtextarea,thi s.form.countdown,
500);"
onKeyDown="limitText(this,this.form.countdown, 500);"
does the same.
[If you are John,
saying "the son of my father named John" is in effect
the same as saying "me".]
The onkeyup in fact is all that is needed.
onKeyUp="limitText(this.form.limitedtextarea,this. form.countdown,
500);">
</textarea>
This works fine:
==================
<script type='text/javascript'>
var max = 500; // or debug with 5
function limitText(limitField, limitCount, limitNum) {
if (limitField.value.length limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
alert('Do not enter more than '+ limitNum +' characters');
};
limitCount.value = limitNum - limitField.value.length;
};
</script>
<form name='myform'>
<textarea name='limitedtextarea'
onKeyUp='limitText(this,this.form.countdown,max);' >
</textarea>
<br><br><input name='countdown' readonly>
</form>
===================
Well, not perfect, if you add letters in the middle, another letter will
be deleted, the one at the end.
And not perfect, because you can add a long sentence by pasting [ctrl-V]
So additional tests have to be done, preferably onsubmit [and also
serverside testing, if Javascript is switched off, or if the clientside
code is manipulated.]
Depending on the OS, a <returnwill count for two, or one character.
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)