'How do I set focus to a text box in Blazor

How do I set focus to a textbox in Blazor? So far the only way we have found is with JavaScript.



Solution 1:[1]

There is no other way to do it... You can use JSInterop to do this, as follows:

 <input type="text" @ref="myref"/>

 @code {

    private ElementReference myref;
    [Inject] IJSRuntime JSRuntime { get; set; }

     protected override async Task OnAfterRenderAsync(bool firstRender)
    {
         if (firstRender)
        {
            await 
        JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", myref);
        }
   }
 }

JavaScript

<script>

    window.exampleJsFunctions =
    {
        focusElement: function (element) {
           element.focus();
        }
    };
</script>

Hope this helps...

Solution 2:[2]

.Net 5 (or higher) makes this easy!

<input type="text" @ref="myref"/>

@code {

    private ElementReference myref;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await myref.FocusAsync();
        }
   }
}

Solution 3:[3]

If you have a built-in type like InputNumber and you are using .Net6, you can apply the solution of @Alexandre but with some changes like this:

<InputNumber @ref="MyRef" @bind-Value="MyValue" />
<button class="btn btn-primary" @onclick="MyClick"> Click me </button>

private InputNumber<int> MyRef;
private int MyValue {get; set;}

//Some click event
private void MyClick()
{
   if(MyRef.Element.HasValue) 
   {
     MyRef.Element.Value.FocusAsync();
   }
}

Solution 4:[4]

This Demo Shows that by clicking on button focus set to textbox.

@page "/setfocus"

<input @ref="textInput" />

<button @onclick="() => 
textInput.FocusAsync()">Set
    focus</button>

@code {
    ElementReference textInput;
}

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 enet
Solution 2
Solution 3 user13256346
Solution 4 M Fa