2
I created a directive to move the cursor to the next field when it reaches the maximum character size, this way below:
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>
<div ng-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, as a 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>
<div ng-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>
In fact, the idea would be to focus on the next input
, but not in the next element. What would be the most practical way to solve this?
The idea is good, but when I (after having filled in all fields) focus on the input (click on the field) and enter some character, it does not go to the next one. Maybe there is still some way to improve the code. + 1
– viana
I understand, it’s just that it wasn’t mentioned in the question, but I can see if I can edit the code to apply the desired effect.
– Wallace Maxters
I’m sorry, but I’ve been going over the @Viana comment and I didn’t see any problem like he said. Whenever the character limit is reached it is moving to the next normal field.
– Sam