1

Is it possible to automatically select the last three characters of an input field when the field receives focus.

For example, the input field has the number "123456". When the field receives focus, I want "456" to be selected so that I can type "789" and the input would then have the value "123789".

I'm using ionic 3.

Simpler
  • 1,317
  • 2
  • 16
  • 31
  • look at [this](https://stackoverflow.com/questions/646611/programmatically-selecting-partial-text-in-an-input-field) SO question, might help... – robbannn Jul 25 '17 at 20:56
  • 1
    Or this.. https://stackoverflow.com/a/10342003/495157 input.setSelectionRange(0, 3); input.focus() – JGFMK Jul 25 '17 at 21:05
  • [Here](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange) is the documentation for `setSelectionRange()` – robbannn Jul 25 '17 at 21:20

2 Answers2

1

This solution uses the ElementRef which comes with a warning as its vulnerable to XSS-attacks. And are to be used as a last resort.

HTML:

<ion-item>
    <ion-input type="text" #testInput (focus)="onFocus()">
    </ion-input>
</ion-item>

TS:

import { Component, ViewChild, ElementRef } from '@angular/core';
...  
export class TestPage{
    @ViewChild('testInput', { read: ElementRef }) input:ElementRef;
    private inputRef;

    constructor(){}

    ionViewDidLoad(){
        this.inputRef = this.input.nativeElement.querySelector('input');
    }

    onFocus(){
        let length = this.inputRef.value.length;

        if(length > 3){
            this.inputRef.setSelectionRange(length - 3, length)
        }
        else{
            this.inputRef.select();
        }
    }
    ...
}
robbannn
  • 5,001
  • 1
  • 32
  • 47
  • 1
    `setSelectedRange` does not work on `type="number"`. I need the input to be of type number so that the number pad is presented to the user. – Simpler Jul 27 '17 at 01:43
  • `type="tel"` works pretty well. The number key pad is presented slightly different, but it's reasonable. – Simpler Jul 27 '17 at 02:39
0

Angular 2+

getLastDigits(value: string): number {
  let digits: string;
  let cutPoint: number;
  if (value.length < 3) return value;
  cutPoint = value.length - 3;
  digits = value.substring(cutPoint);
  return +digits;
}

That should do the trick. this.getLastDigits(value.toString()) to convert number to string when passing the value.

Prav
  • 2,785
  • 1
  • 21
  • 30