Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs move focus to next control on enter

Tags:

angularjs

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 fields and customers are used to hit enter to move to the next input (comming from desktop applications). The angularjs saves the form when the user hits enter. I like to change this. Is it possible ?

like image 419
darpet Avatar asked Aug 06 '13 17:08

darpet


2 Answers

I suggest making a custom directive. Something like this. I haven't tested this.

.directive('focus', 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();
          elem.next().focus();
        }
      });
    }
  }
});

Something like that should work. You might have to tweek something. Good luck.

like image 160
Zack Argyle Avatar answered Oct 11 '22 21:10

Zack Argyle


Create a custom directive:

.directive('nextOnEnter', function () {
    return {
        restrict: 'A',
        link: function ($scope, selem, attrs) {
            selem.bind('keydown', function (e) {
                var code = e.keyCode || e.which;
                if (code === 13) {
                    e.preventDefault();
                    var pageElems = document.querySelectorAll('input, select, textarea'),
                        elem = e.srcElement || e.target,
                        focusNext = false,
                        len = pageElems.length;
                    for (var i = 0; i < len; i++) {
                        var pe = pageElems[i];
                        if (focusNext) {
                            if (pe.style.display !== 'none') {
                                angular.element(pe).focus();
                                break;
                            }
                        } else if (pe === elem) {
                            focusNext = true;
                        }
                    }
                }
            });
        }
    }
})
like image 23
Eduardo Cuomo Avatar answered Oct 11 '22 22:10

Eduardo Cuomo