'JavaScript .focus() function not working in a text field
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!
Solution 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:
- In your component create a variable with the ViewChild annotation
- Mark the element with the ViewChild id in the Components Template
- Access your element in
ngAfterViewInit
like
this.myElement.nativeElement.focus();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Laurenz Honauer |