2017-07-25 56 views
1

當字段接收焦點時是否可以自動選擇輸入字段的最後三個字符。選擇焦點輸入的最後三位數字

例如,輸入字段的編號爲「123456」。當該字段獲得焦點時,我希望選擇「456」,以便我可以鍵入「789」,然後輸入值爲「123789」。

我使用的離子3.

+0

看看[此](https://stackoverflow.com/questions/646611/programmatically-selecting-partial-text - 在一個輸入字段)所以這個問題,可能會有所幫助... – robbannn

+1

或此.. https://stackoverflow.com/a/10342003/495157 input.setSelectionRange(0,3); input.focus() – JGFMK

+0

[這裏](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange)是'setSelectionRange()'的文檔' – robbannn

回答

0

該解決方案使用ElementRef,它隨warning一起提供,因爲它容易受到XSS攻擊。並且將被用作最後的手段。

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

'setSelectedRange'不起作用在'type =「number」'上。我需要的輸入是類型編號,以便數字鍵盤呈現給用戶。 – Simpler

+0

'type =「tel」'工作得很好。數字鍵盤略有不同,但它是合理的。 – Simpler

0

角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; 
 
}

這應該做的伎倆。 this.getLastDigits(value.toString())在傳遞值時將數字轉換爲字符串。