Posted By:
Vijay_Annadi
Posted On:
Monday, November 10, 2003 10:01 AM
To listen for the [ENTER] key, you need to handle the event
onKeyPress (or
onKeyUp or
onKeyDown).
In your event handler function, you should look for keyCode = 13 (which is the [ENTER] key).
Here is a template:
function listenTAKey() {
if(event.keyCode == 13) {
// ENTER has been pressed
}
}
The second part of your question:
In my opinion you would be better off doing this cleanup (I mean, appending blanks to the lines that are of length less than maxlength) upon submission of the form or click of button or something instead of cleaning the lines up in the key event of [ENTER]. Below, you will find the logic of clean up in a couple of JS functions. I havent tested them .. so pardon any mistakes.
function fillToMaxLen() {
var ta = document.theForm.ta;
var val = ta.value;
var MAXLEN = 60;
arrayOfLines = val.split("
");
var newVal = "";
for(var i=0; i var l = arrayOfLines[i];
if(l.length == 0) continue;
if(l.length < MAXLEN) {
l = l + pad(" ",MAXLEN - l.length);
}
newVal += l;
if(i != (arrayOfLines.length - 1)) {
newVal += "
";
}
}
ta.value = newVal;
}
function pad(s, len) {
var ret = "";
for(var i=1; i<=len; i++) {
ret += s;
}
return ret;
}
You can still invoke the clean-up upon [ENTER] key, by doing the following:
and the
listenTAKey() should do this:
function listenTAKey() {
if(event.keyCode == 13) {
// ENTER has been pressed
fillToMaxLen();
}
}
The problem with this is that we clean all the lines in the textarea irrespective of where the [ENTER] key was typed.
This is due to the fact that there is no (at least not that I know of) easy way of capturing where in the textarea was the key pressed.
This was the reason why I was suggesting dealing with this clean-up upon an event apart from [ENTER] key pressed.
I hope that helps.
-- Vijay