JavascriptScript:
<script type="text/javascript">
function limitText(limitField, limitCount, limitNum){
if (limitField.value.length > limitNum)
limitField.value = limitField.value.substring(0, limitNum);
else{
if (limitCount != null)
limitCount.value = limitNum - limitField.value.length;
}
}
</script>
This works:
<form name="myForm">
<textarea name="myTextArea" id="myTextArea" onKeyDown="limitText(this.form.myTextArea, this.form.remCount, 10);"></textarea>
<label name="remCount" id="remCount"></label>
</form>
but this doesn’t:
<textarea name="myTextArea" id="myTextArea" onKeyDown="limitText(this.myTextArea, this.remCount, 10);"></textarea>
<label name="remCount" id="remCount">Chars Left </label>
Using Chrome to debug it, if I don’t use the form method, then the limitField and limitCount are null, but in this.myTextArea is not. Is there anyway to use the function without enclosing the fields in a form? Thanks
Just pass
thisby itself. It’ll be the element itself. To find the “count” label, you can always usedocument.getElementById()to find it.Also, though this isn’t part of your question: be aware that browsers report different values for the length of a textarea when the value includes hard line breaks; that is, line breaks that are present due to the user typing the “Enter” key. Some browsers treat line breaks as being worth 2 characters, because in fact they are two characters long when a
<textarea>is posted back to the server from a form. However, some browsers only report a line break as being 1 character long, even though they follow the relevant spec and send the<textarea>value back with 2-character line breaks.Modern browsers support the
maxlengthattribute on<textarea>elements, but for the reasons outlined above it doesn’t work properly in Chrome and Firefox (though I think a fix is working its way through WebKit).