How can I disabling backspace key press on all browsers?

后端 未结 9 1120
一向
一向 2020-12-15 10:01

I\'m trying to disable the backspace button on an order page in all cases except when a textarea or text input is an active element to prevent users from accidentally backin

相关标签:
9条回答
  • 2020-12-15 10:51

    I think you're overcomplicating that. Rather than checking for an active element, find the event target instead. This should give you the information you need. It's also better to use keydown rather than keypress when there is no visible character. Finally, it's better to use e.preventDefault() for better granularity.

    $(document).keydown(function(e) {
        var nodeName = e.target.nodeName.toLowerCase();
    
        if (e.which === 8) {
            if ((nodeName === 'input' && e.target.type === 'text') ||
                nodeName === 'textarea') {
                // do nothing
            } else {
                e.preventDefault();
            }
        }
    });
    

    NB I could have done this the other way round, rather than an empty if block and all the code going in the else block, but I think this is more readable.

    0 讨论(0)
  • 2020-12-15 10:52

    Seems like the "backspace" will also act as "navigation back" if you have selected radio buttons, check-boxes and body of document as well. Really annoying for forms - especially when using post. All the form could be lost with one slip of the "backspace" key -_- ...

    Honestly... who's idea was it to allow the "backspace as a navigational "back" button!!! really bad idea in my opinion.

    I disable the "backspace" default on anything that is not a text area or text field - like this:

     $(document).keydown(function(e){
    
        console.log(e.keyCode+"\n");
    
        var typeName = e.target.type;//typeName should end up being things like 'text', 'textarea', 'radio', 'undefined' etc.
        console.log(typeName+"\n");
    
    
    
        // Prevent Backspace as navigation backbutton
        if(e.keyCode == 8 && typeName != "text" && typeName != "textarea"){
            console.log("Prevent Backbutton as Navigation Back"+typeName+"\n");
            e.preventDefault();
        }
        //
    
    })
    

    Not sure where else one would want the normal behavior of a back-button other than in these two areas.

    0 讨论(0)
  • 2020-12-15 10:53
    document.onkeydown = KeyPress;
    function KeyPress(e) {
      if (!e.metaKey){
         e.preventDefault();
      }
    }
    
    0 讨论(0)
提交回复
热议问题