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!

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. Commented Apr 28, 2022 at 13:11

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I'm trying to interact with the form via a userscript in Tampermonkey--is it possible to achieve this using plain JavaScript?
In that case i think you can go with querySelectorlike: document.querySelector("#accessionNumber").focus()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.