0

I have the following directive to move to the next input after the field is filled in, for that I have the Following code on my directive:

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

I want to make the opposite of this happen, when pressed to delete/backspace, on mobile input, I want to navigate to the previous input.

My input is as the following illustration:

before filling: _ _ _

after filling (example): 1 2 3

how to make this happen? I am having trouble detecting that delete was pressed.

AnaCS
  • 976
  • 4
  • 15
  • 32

2 Answers2

1

I think this should work

function deleteElementInput() {
   return {
     restrict: 'A',
     link: function($scope, element) {
       element.bind("keydown keypress", function(event) {
         if (event.which === 8 || event.which === 46) {
           if (element.val().length == 0) {
                var $prevElement = element.prev();
                if ($prevElement.length) {
                    $prevElement[0].focus();
                } 
           }
           event.preventDefault();
         }
       });
     }
   }
 };
Shyam Tayal
  • 486
  • 2
  • 13
  • I ended up adding this: .keyup(function (e) { if (e.which === 8 && !this.value) { $(this).prev().focus(); } }); } } }; })(); and it also worked – AnaCS Oct 16 '18 at 13:13
  • 1
    Great , though using jquery is not a great choice but seems perfect if its reducing and satisfying the code :) – Shyam Tayal Oct 17 '18 at 06:23
  • why is query not a good choice? I just want to understand that – AnaCS Oct 17 '18 at 11:50
  • 1
    Becase AngularJS digest cycle wont run if we do any angular DOM manipulation or scope variable manipulation using JQuery. – Shyam Tayal Oct 18 '18 at 04:50
0

I changed my already existing directive to the following:

  function moveNextInput() {
        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();
                        }
                    }
                }).keyup(function (e) {
                    if (e.which === 8 && !this.value) {
                        $(this).prev().focus();
                    }
                });
            }
        }
    };
})();

this works as well for me

AnaCS
  • 976
  • 4
  • 15
  • 32