I've been trying to implement a directive that watch everytime the user hit the keyboard.
I have four different inputs and each of them receives a single character and the user should fill the next form
I wrote a directive for this but it doesn't work
here's my code:
JS:
var app = angular.module('app', []);
app.directive('focus', function() {
return {
restrict: 'A',
link: function($scope,elem,attrs) {
elem.bind('keydown', function(e) {
elem.next().focus();
});
}
}
})
<div ng-app="app">
<form>
<input focus type="text" />
<input focus type="text" />
<input focus type="text" />
</form>
</div>
Solution is quite simple, just add a [0]
after the .next()
:
elem.bind('keydown', function (e) {
elem.next()[0].focus();
});
But you prbly want to use keyup
instead of keydown
, so you enter the value to the old input field before switching to the next one. Updated fiddle: http://jsfiddle.net/Y2XLA/110/
You should also add some handling for the case that elem.next()
is not an input field.