angularjs move focus to next control on enter

后端 未结 10 921
南旧
南旧 2020-11-30 07:07

What is the best way, when hitting enter inside a form, the focus to go to the next input instead submitting the form with angularjs.

I have a form with a lot of fi

10条回答
  •  误落风尘
    2020-11-30 07:17

    Based on the answer by wolcy97 but using only angular

     /** Usage:
      
      
      
      Upon pressing ENTER key the directive will switch focus to
      the next tabindex.
      The last field should not have next-focus directive to avoid
      focusing on non-existing element.
      Works for Web, iOS (Go button) & Android (Next button) browsers, 
    **/ 
     app.directive('nextFocus', [function() {
      return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
          elem.bind('keydown', function(e) {
            var code = e.keyCode || e.which;
            if (code === 13) {
              e.preventDefault();
              try {
                if (attrs.tabindex !== undefined) {
                  var currentTabeIndex = attrs.tabindex;
                  var nextTabIndex = parseInt(currentTabeIndex) + 1;
                  var elems = document.querySelectorAll("[tabindex]");
                  for (var i = 0, len = elems.length; i < len; i++) {
                    var el = angular.element(elems[i]);
                    var idx = parseInt(el.attr('tabindex'));
                    if (idx === nextTabIndex) {
                      elems[i].focus();
                      break;
                    }
                  }
                }
              } catch (e) {
                console.log('Focus error: ' + e);
              }
            }
          });
        }
      };
    }]);
    

提交回复
热议问题