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

后端 未结 9 882
南笙
南笙 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:25

    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.

提交回复
热议问题