How do I disable backspace keystroke if anything other than 2 specific input fields are focused on using jquery?
here is my current code (NOW INCLUDING 2 TEXTBOXES):
The solution of Hudson-Peralta + QF_Developer is great, but it has one flaw:
If your focus is on a radio button or checkbox the backspace button will still throw you back out of the page. Here is a modification to avoid this gap:
$(document).keydown(function(e){
var elid = $(document.activeElement).is('input[type="text"]:focus, textarea:focus');
if(e.keyCode === 8 && !elid){
return false;
};
});
EDIT 20130204:
keypress()
replaced by keydown()
!
The code above now works correctly.
EDIT 20151208:
As mentioned in the comment of @outofmind there are more input types that could throw you back when backspace is pressed. Please add to the comma separated selector list of the is() method any type of input fields that allow direct character input and that are really used in your HTML code, like input[type="password"]:focus
, input[type="number"]:focus
or input[type="email"]:focus
.