I've many input
boxes in a div
and I need to focus one of them programmatically.
How to do it?
It's something like:
<div>
<input type="text" name="txt1" />
<input type="text" name="txt2" />
<input type="text" name="txt3" />
<input type="text" name="txt4" />
<input type="text" name="txt5" />
<input type="text" name="txt6" />
</div>
<button (click)="selectSample()" />
selectSample() {
?????????('txt3').focus();
console.log('Button pressed, txt3 has been selected');
}
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
Input Text focus() MethodThe focus() method is used to give focus to a text field. Tip: Use the blur() method to remove focus from a text field.
JavaScript | Focus()It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.
The hasFocus() method of the Document interface returns a boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.
@Component({
selector: 'my-app',
template: `
<div>
<input #input type="text" name="txt1" />
<input #input type="text" name="txt2" />
<input #input type="text" name="txt3" />
<input #input type="text" name="txt4" />
<input #input type="text" name="txt5" />
<input #input type="text" name="txt6" />
</div>
<button (click)="selectSample()">click</button>
`
})
export class App {
@ViewChildren('input') inputs;
selectSample() {
// console.debug(this.inputs.toArray().find((e) => {
// return e.nativeElement.getAttribute('name') == 'txt3';
//}).nativeElement.value);
this.inputs.toArray().find((e) => {
return e.nativeElement.getAttribute('name') == 'txt3';
}).nativeElement.focus();
}
}
Plunker example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With