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?
Use the onkeydown event and preventDefault() method to Disable Backspace and Delete key in JavaScript. Backspace char code is 8 and deletes key char code is 46.
Use onkeydown property and block key of backspace “8” or key “Backspace” to prevent users from using the backspace key in a textbox using JavaScript.
Use the ALT+LEFT keyboard shortcut instead of Backspace. Set the browser. backspace_action to 0 in the about:config settings panel to re-enable support for the Backspace key as a Back button.
I think this would do the trick:
$(document).keydown(function(e) {
var elid = $(document.activeElement).hasClass('textInput');
if (e.keyCode === 8 && !elid) {
return false;
};
});
assuming that the textboxes has the class 'textInput'.
Here is a working example
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")
$(document).keypress(function(e){
var elid = $(document.activeElement).is("input:focus");
if(e.keyCode === 8 && !elid){
return false;
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With