Forum Moderators: open
Say you've got a <textarea>.
put a "keyup" event handler on it,
which returns false.
Don't you expect that would cancel the action of keyup, hence typing would be disabled?
I tried it, and it's not like that. The keyup event happens, but "return false" does not prevent the textarea from being editable.
What I'm trying to do is limit the length of a textarea, by not allowing the user to type any more characters when the length is greater than x.
I can truncate the textarea value to x characters, but that oddly refreshes the textarea and the caret repositions itself back to the start of the text.
Maybe there's another way to do this?
<h2>Order Notes <span id="charRem">(max 525 characters)</span></h2>
<textarea rows="8" cols="45" name="Notes" id="ordernotes" onkeyup="cntChars(this);"></textarea>
And, the script:
maxStrLen = 525;
function cntChars(which) {
var rem = maxStrLen - which.value.length;
if(which.value.length > maxStrLen) {
rem = 0;
var strLenToDelete = which.value.length - maxStrLen;
if(which.setSelectionRange) {
//Mozilla, Safari, etc
if(which.selectionStart == which.selectionEnd) {
which.selectionStart = which.selectionStart - strLenToDelete;
}//end if
}
else if(document.selection && document.selection.createRange) {
//IE
var txt = document.selection.createRange();
var dump = txt.duplicate();
dump.moveToElementText(which);
dump.setEndPoint('EndToEnd', txt);
which.selectionStart = dump.text.length - strLenToDelete;
which.selectionEnd = which.selectionStart + strLenToDelete;
}
else {
//Opera and others
which.value = which.value.substring(0, maxStrLen);
return;
}//end if
goBackHere = which.selectionStart;
which.value = which.value.substring(0, which.selectionStart) +
which.value.substring(which.selectionEnd, which.value.length);
if(which.setSelectionRange) {
//Mozilla, Safari, etc
which.selectionStart = goBackHere;
which.selectionEnd = which.selectionStart;
}
else {
//IE
txt = which.createTextRange();
txt.move("character", goBackHere);
txt.select();
}//end if
}//end if
document.getElementById('charRem').innerHTML = "(" + rem + " characters remaining)";
}//end function
edit reason: remove side scroll
[edited by: DrDoc at 4:30 pm (utc) on June 19, 2009]