1

I'm trying to use .focus() on the following form field without success. The tabindex of the div this element is in is 0.

<input class="form-control ng-pristine ng-valid ng-empty ng-touched" id="accessionNumber" type="text" name="filter.accessionNumber" ng-model="selectFields.accessionNumber" style="">

I'm using the following:

document.getElementsByName("filter.accessionNumber")[0].focus()

I've also tried document.getElementById using the "accessionNumber" ID as well as the .click() function instead of the .focus() function but none have worked so far

Thanks!

Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
Sam
  • 11
  • 1
  • You should add Angular tag to your question, it might be the reason for your problem. BTW Angular is no longer supported so if you are able to abandon ship, do so soon. – zer00ne Apr 28 '22 at 13:11

1 Answers1

1

Short answer: Maybe have a look at this post

Longer answer: Since you are using Angular you should use the features of the framework that enable this: ViewChild

Steps to make it work:

  1. In your component create a variable with the ViewChild annotation
  2. Mark the element with the ViewChild id in the Components Template
  3. Access your element in ngAfterViewInitlike
this.myElement.nativeElement.focus();
Laurenz Honauer
  • 254
  • 1
  • 12
  • 1
    Thank you! I'm trying to interact with the form via a userscript in Tampermonkey--is it possible to achieve this using plain JavaScript? – Sam Apr 28 '22 at 18:19
  • In that case i think you can go with `querySelector`like: `document.querySelector("#accessionNumber").focus()` – Laurenz Honauer Apr 29 '22 at 06:25