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

后端 未结 9 883
南笙
南笙 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条回答
  •  闹比i
    闹比i (楼主)
    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;
              }
    
        });
    
    

提交回复
热议问题