I created a directive to move the cursor to the next field when it reaches the maximum size of characters, as follows:
var app = angular.module("myApp", []);
app.directive("moverProximoCampo", function() {
return {
restrict: "A",
link: function($scope, element) {
element.on("input", function(e) {
if(element.val().length == element.attr("maxlength")) {
var $nextElement = element.next();
if($nextElement.length) {
$nextElement[0].focus();
}
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script><divng-app="myApp">
<form>
<input type="text" id="part1" ng-model="form.part1" maxlength="3" placeholder="3 caracteres" mover-proximo-campo />
<input placeholder="2 caracteres" type="text" id="part2" ng-model="form.part2" maxlength="2" mover-proximo-campo />
<input placeholder="7 caracteres" type="text" id="part3" ng-model="form.part3" maxlength="7" mover-proximo-campo />
</form>
</div>
But if I put any element between these inputs , such as div
, the next input
is not focused. See:
var app = angular.module("myApp", []);
app.directive("moverProximoCampo", function() {
return {
restrict: "A",
link: function($scope, element) {
element.on("input", function(e) {
if(element.val().length == element.attr("maxlength")) {
var $nextElement = element.next();
if($nextElement.length) {
$nextElement[0].focus();
}
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script><divng-app="myApp">
<form>
<input type="text" id="part1" ng-model="form.part1" maxlength="3" placeholder="3 caracteres" mover-proximo-campo />
<div> Tem uma div aqui entre os inputs</div>
<input placeholder="2 caracteres" type="text" id="part2" ng-model="form.part2" maxlength="2" mover-proximo-campo />
<div> Tem outra div aqui entre os inputs</div>
<input placeholder="7 caracteres" type="text" id="part3" ng-model="form.part3" maxlength="7" mover-proximo-campo />
</form>
</div>
Actually, the idea would be to focus on the next input
, but not on the next element. What would be the most practical way to resolve this?