Svh91
Svh91

Reputation: 73

Javascript Focus() does not work on empty textarea

I'm trying to focus on a textarea when the function below is called. It works as expected when the textarea is filled, but nothing happens when the textarea is empty. I've also tried removing the placeholder, but that made no difference.

Does anyone have an idea how to fix this?

Javascript code:

focusOnText(sampleId: string){
    var textarea = document.getElementById(sampleId);
    textarea.focus();

HTML code:

<textarea class="x" id="sampleId"
          [disabled]="!this.data && !this.editable"
          [readOnly]="!this.editable"
          [(ngModel)]="data"
          placeholder="sample input">{{data}}</textarea>

EDIT:

I left out the edit button, which sets editable to true and calls the focusOnText function. So when the edit button is clicked, [disabled] is false (since not both conditions for [disabled] to be true are met). Hence, I can focus by actually clicking in the textarea, it just doesn't automatically focus when data is null.

I use both [readOnly] and [disabled] so that I can apply specific styling in different scenarios (textarea is blank and non-editable VS. blank and editable).

Upvotes: 5

Views: 1582

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

It should work if you delay slightly the call to focus(). You can avoid using getElementById(id) with the help of a template reference variable txt associated to the textarea element and passed as a parameter to the click event handler:

<textarea #txt class="x"
          [disabled]="!data && !editable"
          [readOnly]="!editable"
          [(ngModel)]="data"
          placeholder="sample input"></textarea>

<button (click)="editable = true; focusOnText(txt)">Edit text</button>

In the code, use setTimeout() to delay the call to focus().

focusOnText(txt: HTMLTextAreaElement) {
  setTimeout(() => {
    txt.focus();
  });
}

If needed, you can set a delay. The example above doesn't specify any delay, but the call is asynchronous nonetheless.

See this stackblitz for a demo.

Upvotes: 4

Related Questions