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):
$(document).keypress(function(e){
var elid = $(document.activeElement).attr('id');
if(e.keyCode === 8 && elid != 'textbox1' || elid != 'textbox2'){
return false;
};
});
this is not working though....any ideas?
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:
EDIT 20130204:
keypress()
replaced bykeydown()
!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
orinput[type="email"]:focus
.@Nick Craver, disgraceful answer for a couple of reasons. Answer the question or at least patronize thoughtfully.
Here is a prototype based solution I ended up using for my forms because users complained that backspace would take them away from the form (which is such an obviously counterintuitive thing to do, one wonders why all browsers use the backspace key as back button).
I think this would do the trick:
assuming that the textboxes has the class 'textInput'.
Here is a working example