How to disable backspace if anything other than in

2020-05-27 10:36发布

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?

9条回答
一纸荒年 Trace。
2楼-- · 2020-05-27 11:28

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.

查看更多
叼着烟拽天下
3楼-- · 2020-05-27 11:29

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

查看更多
混吃等死
4楼-- · 2020-05-27 11:31

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

查看更多
登录 后发表回答