The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault()
. However as the OP alluded to, if you always call it preventDefault()
you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.
Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.
// Bind keydown event to this function. Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){
// Use jquery's constants rather than an unintuitive magic number.
// $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
if (e.keyCode == $.ui.keyCode.BACKSPACE) {
// Filters out events coming from any of the following tags so Backspace
// will work when typing text, but not take the page back otherwise.
var rx = /INPUT|SELECT|TEXTAREA/i;
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
// Add your code here.
}
});