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?
I made a slight change to the accepted answer, which may be of use to someone:
With this method, the user can still navigate using Backspace by holding CTRL, but also it takes into account
textarea
as well as anyinput
.Of course, the alternative is to use something like this instead, which doesn't allow the user to leave the page if they've inputted anything.
I think a slight modification is needed to handle textareas:
Hudson-Peralta's answer worked good for me but I did a small modification since I use many keydown events:
This will disable backspace on your site without having to add specific classes to input boxes. To disable backspace except when using input boxes use .is("input:focus") if you want to disable backspace except when using textarea boxes use .is("input:focus, textarea:focus")
I modified the answer a little bit more to combine everyone's good answer
1. used selector "input[type=text]:focus, textarea: focus" to maintain default behavior for these elements, and as JPsy said, to prevent default behavior on inputs like checkbox
2. used e.target instead to make the code depends more exclusively on JQuery, since I'm not sure if every browser support document.activeElement well
EDIT
3. Include password field also by adding "input[type=password]:focus",
I too have worked hard on the same. Finally, I found the answer and for everybody's convenience I've placed the solution on http://blog.totusinfo.com/jquery-disable-backspace-for-document-history-except-inputs-and-textarea/