Dyego Dyego - 1 year ago 139
Javascript Question

Angularjs - next input on keypress

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:


var app = angular.module('app', []);
app.directive('focus', function() {
return {
restrict: 'A',
link: function($scope,elem,attrs) {

elem.bind('keydown', function(e) {



<div ng-app="app">
<input focus type="text" />
<input focus type="text" />
<input focus type="text" />

Jsfiddle : http://jsfiddle.net/Y2XLA/109/

very similar question: angularjs move focus to next control on enter

Probably it's something simple but I'm not getting it right

Thanks a lot!

Answer Source

Solution is quite simple, just add a [0] after the .next():

    elem.bind('keydown', function (e) {

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.