angularjs move focus to next control on enter

后端 未结 10 924
南旧
南旧 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:32

    This is the directive I ended up with (thanks to Zack Argyle and Oleg):

    app.directive("nextFocus", function () {

        /** Usage:
          
          
          
          Upon pressing ENTER key the directive will switch focus to
          the next field id e.g field2
          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, 
        **/
        var directive = {
            restrict: 'A',
            link: function (scope, elem, attrs) {
                elem.bind('keydown', function (e) {
                    var code = e.keyCode || e.which;
                    if (code === 13) {
                        try {
                            if (attrs.tabindex != undefined) {
                                var currentTabIndex = attrs.tabindex;
                                var nextTabIndex = parseInt(attrs.tabindex) + 1;
                                $("[tabindex=" + nextTabIndex + "]").focus();
                            }
                        } catch (e) {
    
                        }
                    }
                });
            }
        };
        return directive;
    
    });
    

提交回复
热议问题