-->

How to disable backspace if anything other than in

2020-05-27 10:49发布

问题:

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?

回答1:

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



回答2:

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; 
    }; 
});


回答3:

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.



回答4:

I think a slight modification is needed to handle textareas:

var elid = $(document.activeElement).is("input:focus, textarea:focus"); 


回答5:

I made a slight change to the accepted answer, which may be of use to someone:

$(document).keydown(function(e) {
    var elid = $(document.activeElement).is("input, textarea") ;
    if (e.keyCode === 8 && !elid) {
        if(e.ctrlKey) {
            window.history.back()
        }
        else {
            alert("Navigating with Backspace has been disabled. Use CTRL + Backspace if you want to go back to the previous page (and lose any unsaved changes).");
            return false;
        }
    }
});

With this method, the user can still navigate using Backspace by holding CTRL, but also it takes into account textarea as well as any input.

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.



回答6:

@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).




        // event handlers must be attached after the DOM is completely loaded
        Event.observe(window, 'load', function() {
          // keypress won't fire for backspace so we observe 'keydown'
          Event.observe(window, 'keydown', function(event){
            // 8 == backspace
            if( event.keyCode == 8) {
                // with no field focused, the target will be HTMLBodyElement
               if( event.target == document.body) {
                  // stop this event from propagating further which prevents                      
                  // the browser from doing the 'back' action
                  event.stop();
               }
             }
          });
        });



回答7:

Hudson-Peralta's answer worked good for me but I did a small modification since I use many keydown events:

$(document).keydown(function(e){ 
            var elid = $(document.activeElement).is("input:focus"); 
            if(e.keyCode === 8 && !elid){ 
               e.preventDefault(); 
            }; 
        });


回答8:

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/



回答9:

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",

     $(document).keydown(function(e){

          var code=e.keyCode;
          var is_to_stop= (!$(e.target).is("input[type=text]:focus, input[type=password]:focus, textarea:focus")) && (code==8);
          if(is_to_stop){
            return false;
          }

    });