最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to clear an input value on some button press? - Stack Overflow

programmeradmin2浏览0评论

I'm trying to clear an input when a user presses comma (,). So what I did was, on (keypress) I would check the keyCode and if it's a comma I would clear the input by setting the input value to input.value = ''.

HTML:

<input type="text" #elem (keypress)="clearInput($event)">

Code:

@ViewChild( 'elem' ) public element;

clearInput( e: KeyboardEvent ) {
 if ( e.keyCode === 44 ) {
    this.element.nativeElement.value = '';
 } else {
   console.log('Not a comma');
 }
}

I'm trying to clear an input when a user presses comma (,). So what I did was, on (keypress) I would check the keyCode and if it's a comma I would clear the input by setting the input value to input.value = ''.

HTML:

<input type="text" #elem (keypress)="clearInput($event)">

Code:

@ViewChild( 'elem' ) public element;

clearInput( e: KeyboardEvent ) {
 if ( e.keyCode === 44 ) {
    this.element.nativeElement.value = '';
 } else {
   console.log('Not a comma');
 }
}
Share Improve this question edited Oct 17, 2019 at 10:06 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Aug 8, 2018 at 10:46 user3607282user3607282 2,5556 gold badges37 silver badges65 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 11

Use Event.preventDefault().

Add preventDefault() in your clearInput code as shown below:

clearInput (e: KeyboardEvent) {
   if (e.keyCode === 44) {
      e.preventDefault();     // <-- Here
      this.element.nativeElement.value = '';
   } else {
      console.log('Not a comma');
   }
}

Simply return false if a comma is pressed:

class HomeComponent {
  @ViewChild('elem') public element;
  clearInput(e: KeyboardEvent) {
    if (e.keyCode === 44) {
      this.element.nativeElement.value = '';
      return false;
    } else {
      console.log('Not a comma');
    }
  }
}

JSFiddle: https://jsfiddle.net/lucakiebel/zrehcwfy/1/

You need to do 2 minor changes:

  1. Use keyup event to get the latest key typed and include in the value of input
  2. Use e.key === ',' in the if condition

Here is the working JSFIDDLE

发布评论

评论列表(0)

  1. 暂无评论