Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear an input value on some button press?

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');
 }
}
like image 381
user3607282 Avatar asked Aug 08 '18 10:08

user3607282


People also ask

How do I add a Clear button to the input field?

The easiest way to add an input box with a clear button is to add an input element with the type attribute set to search . Then when we type into the input box, we see the clear button displayed. And we can click on it to clear its value.

How do you reset input element?

The HTMLFormElement. reset() method restores a form element's default values. This method does the same thing as clicking the form's <input type="reset"> control. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method.


2 Answers

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');
   }
}
like image 67
UtkarshPramodGupta Avatar answered Sep 22 '22 09:09

UtkarshPramodGupta


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/

like image 20
Luca Kiebel Avatar answered Sep 25 '22 09:09

Luca Kiebel