Prevent backspace from navigating back in AngularJS

后端 未结 4 1567
Happy的楠姐
Happy的楠姐 2021-01-12 12:03

I faced this issue in my AngularJS webapp.

When a user enters a page with a form to fill and he starts typing, if he presses the backspace key and the focus is not o

相关标签:
4条回答
  • 2021-01-12 12:41

    I got this answer here: How can I disabling backspace key press on all browsers?

    $(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();
            }
        }
    });
    

    Just put it inside your controller.

    0 讨论(0)
  • 2021-01-12 12:45

    There is $document in angular js:

    angular.module('yourModule', [])
      .controller('yourController', ['$scope', '$document', function($scope, $document) {
          $document.on('keydown', function(e){
              if(e.which === 8 && ( e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT" ) ){ // you can add others here inside brackets.
                  e.preventDefault();
              }
          });
    
        }
      ]);
    

    Plnkr Demo.

    You can see in the demo i have used only for "INPUT" nodeName and it does not prevent the default of the backspace key on text input but not on textarea because we have not handled it in the condition.

    0 讨论(0)
  • 2021-01-12 12:54

    Add the below script in your controller

    var rx = /INPUT|SELECT|TEXTAREA/i;
    
    $document.on("keydown keypress", function(e){
        if( e.which == 8 ){ // 8 == backspace
            if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
                e.preventDefault();
            }
        }
    });
    

    Or you can use Jquery

      $(function(){
          var regx = /INPUT|SELECT|TEXTAREA/i;
    
          $(document).bind("keydown keypress", function(e){
              if( e.which == 8 ){ // 8 == backspace
                  if(!regx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
                      e.preventDefault();
                  }
              }
          });
      });
    
    0 讨论(0)
  • 2021-01-12 13:02

    I can't comment "accepted answer", but it will work not right, as condition

    e.which === 8 && e.target.nodeName !== "INPUT" || e.target.nodeName !== "SELECT"
    

    with logic error, so you can use

    e.which === 8 && e.target.nodeName !== "INPUT" && e.target.nodeName !== "SELECT"
    

    or answer that wrote @ThisIsMarkSantiago.

    0 讨论(0)
提交回复
热议问题