How do I set focus to a textbox in Blazor? So far the only way we have found is with JavaScript.
.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();
}
}
}
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();
}
}
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