Search code examples
angularjsionic-frameworkionic-popup

Angular/Ionic : change input focus after completion


In order for users to lon into my application, I send them a code (6 numbers) by SMS. When coming back to the application, I display a popup in order for them to input the said code. I would like to have 6 inputs (maxlength=1) for a better design. Here is the visual I would like to have :

enter image description here There is my (so-far) HTML template of the popup :

<ion-content class="content-activation-code">
<div class="activation-code-list">
    <input type="text" class="activation-input-code" maxlength="1" ng-model="code.c1" ng-focus="code.c1===''">
    <input type="text" class="activation-input-code" maxlength="1" ng-model="code.c2">
    <input type="text" class="activation-input-code" maxlength="1" ng-model="code.c3" >
    <input type="text" class="activation-input-code" maxlength="1" ng-model="code.c4" >
    <input type="text" class="activation-input-code" maxlength="1" ng-model="code.c5" >
    <input type="text" class="activation-input-code" maxlength="1" ng-model="code.c6" >
</div>

CSS for this template :

/*Popup code*/
.content-activation-code{
    margin-top:55px;
}
    .activation-code-list{
        text-align:center;
    }
    .content-activation-code .activation-input-code{
        width:20px;
        border:1px solid grey;
        margin:2px;
        border-radius:10px;
        text-align:center;
        display:inline;
    }

And the controller in charge of displaying the popup :

$scope.code = {c1:"",c2:"",c3:"",c4:"",c5:"",c6:""};

    $ionicPopup.show({
        templateUrl: "templates/activation_code.html",
        title: 'Pour activer votre compte',
        subTitle: 'Entrez le code envoyé au XXXX',
        scope: $scope,
        buttons: [
            { text: 'Annuler' },
            {
              text: 'Activer',
              type: 'button-positive',
              onTap: function(event) {
                console.log($scope.code);
              }
            }
          ]
    });

For the user to not hate me and actually log into the application, I would like to implement a kind of directive doing as follow : - Focus on first input when popup opens - Focus on next input everytime the previous is completed - Focus on previous input everytime the next one is deleted and backspace is pressed

Tip : I already tried puting a background-image into the input to simulate this behavior, but it didn't show up right on the phone.

I'm using Angular 1.5.3


Solution

  • You need add directive on each input that just trigger focus on next one

     elem.on(keypress, function(e) {
       e.target.nextElementSibling.focus().select();
     })
    

    Example JSFiddle