![](/img/trans.png)
[英]AngularJS directive for text input: focus on next input on Enter
[英]change focus to the next input text with angularjs
我的控制器中有一個對象變量(var myObject),在IHM中分為3個輸入文本。
我想在焦點到達maxLength時自動將焦點更改為下一個輸入。
var myObject = {
part1:"",
part2:"",
part3:""
}
<form>
<input type="text" id="part1" ng-model="myObject.part1" maxlength="7"/>
<input type="text" id="part2" ng-model="myObject.part2" maxlength="12"/>
<input type="text" id="part2" ng-model="myObject.part2" maxlength="12"/>
</form>
你需要使用一個指令:
app.directive("moveNextOnMaxlength", 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();
}
}
});
}
}
});
並按如下方式更新您的表單:
<form>
<input type="text" id="part1" ng-model="myObject.part1" maxlength="7" move-next-on-maxlength />
<input type="text" id="part2" ng-model="myObject.part2" maxlength="12" move-next-on-maxlength />
<input type="text" id="part2" ng-model="myObject.part2" maxlength="12"/>
</form>
您可以將指令移動到<form>
元素上,但build-int jqLite的find()
方法將限制您僅按標記名稱查找元素。 如果你正在使用完整的jQuery,或者可以使用vanillaJS,我建議使用這種方法。
接受的答案有效,但前提是這些字段是直接的兄弟姐妹。 例如,如果您自己的列中有3個字段,則需要使用不同的解決方案:
angular
.module('move-next-directive', [])
.directive('moveNextOnMaxlength',
function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
elem.on('input', function(e) {
var partsId = attrs.id.match(/focus(\d+)/);
var currentId = parseInt(partsId[1]);
var l = elem.val().length;
if (l == elem.attr("maxlength")) {
nextElement = document.querySelector('#focus' + (currentId + 1));
nextElement.focus();
}
});
}
}
}
);
為每個輸入字段添加一個帶編號的“焦點”ID:
<div class="row">
<div class="col-xs-4">
<input type="text" id="focus1" maxlength="4" move-next-on-maxlength />
</div>
<div class="col-xs-4">
<input type="text" id="focus2" maxlength="4" move-next-on-maxlength />
</div>
<div class="col-xs-4">
<input type="text" id="focus3" maxlength="4" />
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.