Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable backspace if anything other than input field is focused on using jquery

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?

like image 826
sadmicrowave Avatar asked Apr 15 '10 13:04

sadmicrowave


People also ask

How do I restrict Backspace in JavaScript?

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.

How do I turn off input backspace?

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.

How can I prevent the Backspace key from navigating back?

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.


2 Answers

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

like image 142
Karl Johan Avatar answered Nov 01 '22 00:11

Karl Johan


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; 
    }; 
});
like image 29
Hudson-Peralta Avatar answered Nov 01 '22 00:11

Hudson-Peralta