change focus to the next input text with angularjs

后端 未结 2 644
执念已碎
执念已碎 2021-01-12 14:51

I have an object variable in my controller (var myObject), divided into 3 input text in the IHM.

I want to change automatically the focus to the next input when the

2条回答
  •  粉色の甜心
    2021-01-12 15:12

    Accepted answer works, but only if the fields are immediate siblings. If for example you have 3 fields each in there own column, you need a different solution:

    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();
              }
            });
          }
        }
      }
    );
    

    Add a numbered "focus" id to each input field:

    Credits to this answer: https://stackoverflow.com/a/33007493/3319392

提交回复
热议问题