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

后端 未结 9 900
南笙
南笙 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: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();
                   }
                 }
              });
            });
    
    

提交回复
热议问题