How to unselect input content when focus on it by pushing tab key?

1.3k views Asked by At

In an html form, When you use tab to go on next input it select all the content by default, How to unselect it?

3

There are 3 answers

0
Disdier Alexandre On BEST ANSWER

Just set target.selectionEnd to 0 on focus event

<input (focus)="unselectOnFocus($event)">
unselectOnFocus(event: Event): void {
  event.target.selectionEnd = 0;
}
0
praveen kaushik On

For setting the elements as unselectable, you can use tabindex = -1 attribute in the input element like following-

<input tabindex='-1'>

A negative value (usually tabindex="-1") means that the element is not reachable via sequential keyboard navigation, but could be focused with Javascript or visually by clicking with the mouse.

You can check more about this here- tabindex MDN guide

Hope this will help you.

0
Kraken On

Set #myInput and bind the focus event <input #myInput (focus)="onFocus()">

@ViewChild('myInput') myInput: ElementRef<HTMLInputElement>;

and

onFocus() {
    setTimeout(() => {
      this.myInput.nativeElement.setSelectionRange(0,0);
    }, 0)
}

The timeout is required because when you select an input with the tab key, the text is automatically selected right after the focus event.