Handling Backspace Key Press
Capturing keyboard events can be tricky in a cross-browser sense. NN4 and IE not only have different ways of accessing keyboard character information, but their event objects and corresponding property names are completely different.
In this example, we're trying to limit the number of characters that can be typed into a textarea. For the sake of accuracy, the script is capturing keyboard character codes so that it can test to see if the backspace was pressed, and if so, adjust the value of the counter text field. In IE, only the onKeyUp and onKeyDown handlers generate an event object for non-alphanumeric keys such as backspace. If you need to test for an alphanumeric character, the onKeyPress event handler must be used.
var prevValue=0
function characterLimit(e) {
if(e){
e = e
}
else {
e = window.event
}
if(e.which){
var keycode = e.which
}
else {
var keycode = e.keyCode
}
if(keycode==8){
if(prevValue>0){
prevValue-=1
}
}
else{
prevValue+=1
}
document.formOne.textlength.value = "prevValue: "+prevValue
var constant
if (prevValue <= 10) {
constant = 10-prevValue
document.formOne.counter.value = "Remaining characters: " + constant
}
else {
constant = prevValue-10
document.formOne.counter.value = "Overlimit by: " + constant + " characters"
}
}
View the Source