Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the focus to an InputText element?

Using the example from the Microsoft docs, I'm trying to programmatically set the focus to an input element.

Unfortunately, the example uses a standard <input type="text"> whereas I want to use it for an InputText element.

The Microsoft example uses an extensions method that takes an ElementReference:

public static Task Focus(this ElementReference elementRef, IJSRuntime jsRuntime)
{
    return jsRuntime.InvokeAsync<object>(
        "exampleJsFunctions.focusElement", 
        elementRef);
}

Using an InputText, I see no way of obtaining such an ElementReference.

Providing my own Focus() overload with an InputText instead, compiled but showed no visual result. Therefore I'm clueless.

My question

How can I programmatically set the focus to an InputText element?

like image 561
Uwe Keim Avatar asked Dec 02 '19 11:12

Uwe Keim


People also ask

How do you set focus on an element?

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.

How do you set the focus on an element in react?

To focus input when another element is clicked in React:Set the onClick prop on the other element. When the other element is clicked, focus the input, e.g. ref. current. focus() .

How do you set the focus on an element in Blazor?

To set the focus to a HTML element in Blazor, use the JavaScript interop to pass the HTML element and then use focus JavaScript method.

How do you focus an input element on page load?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.


1 Answers

In .NET5 it will be much simpler:

<button @onclick="() => textInput.FocusAsync()">Set focus</button>
<input @ref="textInput"/>
@code {
    ElementReference textInput;
}

NOTE: this feature was introduced in .NET5 Preview 8 so might change until the final release!

Also worth mentioning that in .NET5 RC1 JavaScript isolation was introduced via JS Module export/import. So if you still need to use JS interop do not pollute window object.

Update: .NET 5 was released and this feature works unchanged.

Also I have a cool Nuget package which can do some convenient JS tricks for you e.g.: focusing previously active element without having a @ref to it. See docs here.

like image 173
Major Avatar answered Sep 21 '22 12:09

Major