How to focus on next field automatically?

Viewed 499

I'm asking user to type a code received by SMS in separated fields.

This way:

<ion-input type="text" inputmode="numeric" maxlength="1" [(ngModel)]="field1" name="field1" (ionChange)="eventIonChange($event, 2)" (ionFocus)="eventIonFocus($event)" autofocus="true"></ion-input>
<ion-input type="text" inputmode="numeric" maxlength="1" [(ngModel)]="field2" name="field2" (ionChange)="eventIonChange($event, 3)" (ionFocus)="eventIonFocus($event)"></ion-input>
<ion-input type="text" inputmode="numeric" maxlength="1" [(ngModel)]="field3" name="field3" (ionChange)="eventIonChange($event, 4)" (ionFocus)="eventIonFocus($event)"></ion-input>
<ion-input type="text" inputmode="numeric" maxlength="1" [(ngModel)]="field4" name="field4" (ionChange)="eventIonChange($event)" (ionFocus)="eventIonFocus($event)"></ion-input>

So, how can I change the focus when user type one caharcter in each field?

I'm trying something like:


field1:string = '';
field2:string = '';
field3:string = '';
field4:string = '';

...

eventIonFocus(e) {
  e.target.value = '';
}

eventIonChange(e, nextElement) {
  if(nextElement){
    let element = (<HTMLInputElement>document.getElementById('field2'));
    element.setFocus();
  }
}
1 Answers

You can do this using ViewChild as follows.

HTML

 <ion-input #field1 type="text" inputmode="numeric" [(ngModel)]="smsCode.first" maxlength="1" (ionChange)="eventIonChange(2)"></ion-input>
 <ion-input #field2 type="text" inputmode="numeric" [(ngModel)]="smsCode.second" maxlength="1" (ionChange)="eventIonChange(3)"></ion-input>
 <ion-input #field3 type="text" inputmode="numeric" [(ngModel)]="smsCode.third" maxlength="1" (ionChange)="eventIonChange(4)"></ion-input>
 <ion-input #field4 type="text" inputmode="numeric" [(ngModel)]="smsCode.fourth" maxlength="1"></ion-input>

 <button ion-button (click)="onSubmit()">SUBMIT</button>

TS

export class HomePage {

  @ViewChild('field1') field1;
  @ViewChild('field2') field2;
  @ViewChild('field3') field3;
  @ViewChild('field4') field4;

  smsCode: any =  { first: '', second: '', third: '', fourth: '' };

  constructor() {

  }

  ngAfterViewInit() {
    setTimeout(() => this.field1.setFocus(), 500 )
  }

  eventIonChange(next) {

    switch(next) {

      case 2:
        this.field2.setFocus();
        break;

      case 3:
        this.field3.setFocus();
        break;

      case 4:
        this.field4.setFocus();
        break;

    }
  }

  onSubmit() {
    // Do your implementation with user inputs here
    console.log(JSON.stringify(this.smsCode, null, 2));
  }

}

Changes are pretty big. But you will be ok with it.

Find StackBlitz Demo.

Related