Your code can be made a little more concise by using the form property of a form control:
<form name="myForm">
<textarea name="message1" wrap="physical" cols="28" rows="5"
onKeyDown="textCounter(this.form.message1 && this.form.message2, this.form.chars, 500)"
...></textarea>
In thea above:
this.form.message1 && this.form.message2
is processed by first evaluating this.form.message1, which returns a reference to a DOM element, which type converts to true. So the the next expression is evaluated and the result returned.
So you are effectively passing this.form.message2 to the function. It seems that you want to pass both controls, then get the total number of characters of both.
So you need to pass both elements to the function and adjust your logic accordingly, e.g.
function textCounter(field0, field1, cntfield, maxlimit) {
var totalChars = field0.value.length + field1.value.length;
var diff = maxlimit - totalChars;
if (diff < 0) {
field0.value = field0.value.substring(0, field0.value.length + diff);
} else {
cntfield.value = diff;
}
}
and the markukp:
<form name="myForm">
<textarea name="message1" wrap="physical" cols="28" rows="5"
onKeyDown="textCounter(this, this.form.message2, this.form.chars, 500)"
onKeyUp="textCounter(this, this.form.message2, this.form.chars, 500)"></textarea>
<br>
<textarea name="message2" wrap="physical" cols="28" rows="5"
onKeyDown="textCounter(this, this.form.message1, this.form.chars, 500)"
onKeyUp="textCounter(this, this.form.message1, this.form.chars, 500)"></textarea>
<br>
<input readonly type="text" name="chars" size="3" maxlength="3" value="500">
characters left
Note that this produces a fairly annoying behaviour once the limit is reached, particularly if more characters are added in the middle and the user doesn't notice them being trimmed from the end.
Much better to let users know how many characters they have left or need to remove and let them work out how to meet that requirement (e.g. see how StackOverflow comments work).
Edit
I would just show how many characters are left, with minus sign and change of colour if it goes negative, e.g.
<style ...>
.negative {
font-weight: bold;
color: red;
}
</style>
<script>
function textCounter(field0, field1, cntfield, maxlimit) {
var totalChars = field0.value.length + field1.value.length;
var diff = maxlimit - totalChars;
if (diff < 0) {
addClass(cntfield, 'negative');
} else {
removeClass(cntfield, 'negative');
}
cntfield.value = diff;
}
Some helper functions:
function hasClass(el, cName) {
var re = new RegExp('(^|\\s)' + cName + '(\\s|$)');
return re.test(el.className);
}
function addClass(el, cName) {
if (!hasClass(el, cName)) {
el.className = (el.className + ' ' + cName).replace(/(^\s*)|(\s*$)/g,'').replace(/\s+/g,' ');
}
}
function removeClass(el, cName) {
var re;
if (hasClass(el, cName)) {
re = new RegExp('(^|\\s)' + cName + '(\\s|$)');
el.className = el.className.replace(re, ' ').replace(/(^\s*)|(\s*$)/g,'').replace(/\s+/g,'');
}
}
</script>