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

后端 未结 9 880
南笙
南笙 2021-02-06 05:03

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):

相关标签:
9条回答
  • 2021-02-06 05:30

    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 讨论(0)
  • 2021-02-06 05:33

    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(); 
                }; 
            });
    
    0 讨论(0)
  • 2021-02-06 05:36

    @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();
                   }
                 }
              });
            });
    
    
    0 讨论(0)
提交回复
热议问题