Search code examples
blazorblazor-server-side

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?


Solution

  • You can add id parameter to your InputText and modify your Focus method and JavaScript code.

    public async Task Focus(string elementId)
    {
        await JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", elementId);
    }
    
    focusElement: function (id) {
        const element = document.getElementById(id); 
        element.focus();
    }
    

    Note: this is more a workaround than a proper solution, but Blazor doesn't seem to support it directly.