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 prevValue is set outside function so that it is not set back to zero each time function is invoked
function characterLimit(e) { // event object is being passed from function call
if(e){ // if the event object is present (NN only)
e = e // var e = event
}
else {
e = window.event // else e = winddow.event for IE
}
if(e.which){ // if there is syntax support for the property 'which' (NN only)
var keycode = e.which // e.which is stored in variable "keycode"
}
else {
var keycode = e.keyCode // otherwise for IE, var keycode stores e.keyCode syntax
}
if(keycode==8){ // keycode for backspace is 8, so if backspace is pressed,
if(prevValue>0){
prevValue-=1 // prevValue variable equals itself minus one
}
}
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