开发者

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.key开发者_Python百科Code === 8 && elid != 'textbox1' || elid != 'textbox2'){
      return false;
  };
});

this is not working though....any ideas?


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


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.


I think a slight modification is needed to handle textareas:

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


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.


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


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


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/


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

    });

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜