Using the enter key as a tab, using only angular and jqlite

I reviewed several threads and tried many solutions. Honestly, I think I'm losing my mind.

I have ng-repeat with inputs. All that should happen is that when the user presses the enter button, he should switch the focus to the next input, basically simulating the functionality of the tab.

Code (incomplete): HTML:

<body ng-app="ap" ng-controller="con"> <table> <tr> <th>Name</th> <th>Age</th> </tr> <tr ng-repeat='person in persons'> <td> <input type='text' name="personName" ng-model="person.name" /> </td> <td> <input type='number' name="personName" ng-model="person.age" enter-as-tab /> </td> </tr> </table> 

JS:

  var app = angular.module("ap", []); app.controller("con", function ($scope) { $scope.persons = [ { name: 'Susan', age: 1 }, { name: 'Peter', age: 1 }, { name: 'Jack', age: 2 } ]; }); app.directive('enterAsTab', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { if(event.which === 13) { event.preventDefault(); // Go to next age input } }); }; }); 

Here is the link to the script: fiddle

+5
source share
2 answers

Ok, so I figured it out. In the end, it was not so difficult. Just got into all the “don't think jQuery using Angular” thinking.

Here is the directive that I followed:

 app.directive('enterAsTab', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { if(event.which === 13) { event.preventDefault(); var elementToFocus = element.next('tr').find('input')[1]; if(angular.isDefined(elementToFocus)) elementToFocus.focus(); } }); }; }); 

Here is a link to a working script: enter-as-tab

+10
source

Starting with @avn's solution, I made some changes to find recursively and focus on the next input text or input number, but only if the value is valid, or submit the form. Designed for ionic forms, but can be adapted for any angular forms:

 app.directive('enterAsTab', function () { return { restrict: 'A', require: '^ngModel', link: function (scope, element, attrs, ctrl) { element.bind("keydown keypress", function (event) { function isKeyEnterAndValid(){ return event.which === 13 && ctrl.$valid; } function nextItem(div, tag){ var next = div.next(tag); if (!next) return nextItem(div, 'label'); return next; } function isTypeTextOrNumber(input){ return ['text', 'number'].indexOf(input.attr('type')) === -1; } function findInput(div){ var next = nextItem(div, 'div'); if (!next) return; var input = next.find('input'); if (!input || isTypeTextOrNumber(input)){ return findInput(next); } return input[0]; } if(isKeyEnterAndValid()) { var nextInput = findInput(element.parent()); if(angular.isDefined(nextInput)){ event.preventDefault(); nextInput.focus(); } } }); } }; }); 
0
source

Source: https://habr.com/ru/post/1204327/


All Articles