Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 811
Noel Avatar asked Sep 05 '25 16:09

Noel


2 Answers

.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();
        }
   }
}
like image 155
Alexandre Avatar answered Sep 11 '25 01:09

Alexandre


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();
   }
}
like image 29
Nb777 Avatar answered Sep 11 '25 02:09

Nb777



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!