Skip to content

Instantly share code, notes, and snippets.

@rattanchauhan
Last active December 19, 2019 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattanchauhan/9a0f4e97523afa6eab7e07ff4d084611 to your computer and use it in GitHub Desktop.
Save rattanchauhan/9a0f4e97523afa6eab7e07ff4d084611 to your computer and use it in GitHub Desktop.
AngularJs | Directive for Auto Focus Next element on Enter
var app = angular.module("myApp", []);
app.directive("moveNextOnEnter", function() {
return {
restrict: "A",
link: function($scope, element) {
element.bind("keyup", function(e) {
if (e.which == 13) {
var $nextElement = element.next();
if($nextElement.length) {
$nextElement[0].focus();
}
}
});
}
}
});
// USAGE
<div ng-app="myApp">
<form>
<input type="text" id="part1" ng-model="myObject.part1" maxlength="7" move-next-on-enter />
<input type="text" id="part2" ng-model="myObject.part2" maxlength="12" move-next-on-enter />
<input type="text" id="part3" ng-model="myObject.part3" maxlength="12"/>
</form>
</div>
@nicostubi
Copy link

Hello,

It works fine with IE 11.

However, it does not work with Firefox, especially this version:
image

The error is "event is not defined".

BR,
Nicolas

@rattanchauhan
Copy link
Author

rattanchauhan commented Dec 19, 2019

Hi Nicolas,

I haven't updated this snippet for the last 3 years so I can't be sure if this works with the latest builds. If you find an improvement do let me know.

Thanks,
Rattan

@nicostubi
Copy link

Hi Rattan,

event.preventDefault(); was the problem.

I got rid of this line, as I do not really need it.

BR,
Nicolas

@rattanchauhan
Copy link
Author

Great. thanks a lot, I'll update the gist as this part is totally optional.

Thanks,
Rattan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment