Reputation: 1447
I would like to disable the backspace key (keycode 8) for any element except textboxes and textareas.
Here is what I tried without success:
$(":not(input, textarea)").keydown(function(event) {
if (event.keyCode == 8) {
event.preventDefault();
return false;
}
});
...
$("*:not(input, textarea)").keydown(function(event) {
if (event.keyCode == 8) {
event.preventDefault();
return false;
}
});
..
$("body").not("input,textarea").keydown(function(event) {
if (event.keyCode == 8) {
event.preventDefault();
return false;
}
});
The idea is to avoid the user to accidentally hit the backspace key while not focused in any textbox or textarea.
Any thoughts?
Upvotes: 3
Views: 13215
Reputation: 653
You also want to disable for text areas or textboxes that are readonly.
If text areas or text boxes are readonly and have focus then hitting backspace will cause you to leave the page as well. That is why you should also check for readonly.
I'm assuming your trying to prevent back functionality.
EDIT:
You could also attach the listener to the body as well. EDIT2: you need to prevent action on checbox too (which is input)
$(document).keydown(function (e) {
var element = e.target.nodeName.toLowerCase();
if ((element != 'input' && element != 'textarea') || $(e.target).attr("readonly") || (e.target.getAttribute("type") ==="checkbox")) {
if (e.keyCode === 8) {
return false;
}
}
});
Upvotes: 6
Reputation: 941
The easiest solution (which covers all the special cases) is:
$(document).keydown(function(e) {
if (e.which == 8 && !$(':focus').length) {
e.preventDefault();
}
});
Upvotes: 2