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

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

    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.

提交回复
热议问题