How do I set focus to a text box in Blazor
Asked Answered
P

6

24

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

Perlis answered 19/2, 2020 at 21:3 Comment(2)
Here it is: https://mcmap.net/q/582088/-how-to-detect-key-press-without-using-an-input-tag-in-blazorMonth
Does this answer your question? How to set the focus to an InputText element?Restrainer
A
2

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...

Achaemenid answered 19/2, 2020 at 21:37 Comment(1)
see below answerOrosco
O
44

.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();
        }
   }
}
Overcasting answered 3/12, 2020 at 21:0 Comment(4)
Many examples for FocusAsync fail to mention that it must be called in the OnAfterRenderAsync method (as Alexandre shows). Also don't miss that FocusAsync has an optional bool arg that scrolls the focused element into view.Brigade
Works great! I'm posting an answer for Radzen components below (it's slightly different, but needs to be shared here).Aniela
".Net 5 (or higher)" - what's the net5 requirement here?Plenish
I see the FocusAsync extension method was introduced in (aspnet) net5. (The overload with param in net6.)Plenish
P
7

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();
   }
}
Prudish answered 9/5, 2022 at 7:45 Comment(0)
A
3

For those of us using a 3rd party control, the provider should have an equivalent element reference to make Alexandre's answer work (DotNet5 and up)

<RadzenTextBox @ref="searchBox" Name="SearchPhrase" @bind-Value=@SearchString MaxLength="400" @oninput=@(args => OnChangedSearch(args.Value.ToString())) @onkeydown="@Enter" />
        
     @code{   
            RadzenTextBox searchBox;
            protected override async Task OnAfterRenderAsync(bool firstRender)
            {
                if (firstRender)
                {
                    await searchBox.Element.FocusAsync(); //NOTE: this is for Radzen "elements"
                }
            }
        }
Aniela answered 19/1, 2023 at 21:21 Comment(1)
What if they don't?Carlos
A
2

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...

Achaemenid answered 19/2, 2020 at 21:37 Comment(1)
see below answerOrosco
G
1

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;
}
Gurkha answered 29/5, 2022 at 4:36 Comment(1)
As several other questions/answers have pointed out, this does not always work. You need to defer the FocusAsync call until OnAfterRenderAsync #72411971Monastery
L
0

In .NET 7 Maui Blazor, this worked when I tested.

  1. Put the following Js method in index.html inside script tag 'text/javascript'

     window.exampleJsFunctions =
     {
         focusElement: function (elementId) {
             var el = document.getElementById(elementId);
             if (!!el) {
                 el.focus();
             }
         }
     };
    
  2. Add the following method to a .razor file, say the element urlTextRef should be focused

    private InputText urlTextRef;
    
     protected override async Task OnAfterRenderAsync(bool firstRender)
     {
             if (firstRender)
             {
                 await JS.InvokeVoidAsync("exampleJsFunctions.focusElement", urlTextRef?.Element?.Id);
             }
     }
    

This override uses a InputText and sets an id.

   <InputText @ref="urlTextRef" id="articleUrl" @bind-Value="Model!.ArticleUrl" placeholder="Skriv inn url til artikkel i Dagbladet" />
Leuco answered 17/9, 2023 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.