How to set the focus to an InputText element?

18,065

Solution 1

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.

Solution 2

In .NET5 it will be much simpler:

<button @onclick="() => textInput.FocusAsync()">Set focus</button>
<input @ref="textInput"/>
@code {
    ElementReference textInput;
}

NOTE: this feature was introduced in .NET5 Preview 8 so might change until the final release!

Also worth mentioning that in .NET5 RC1 JavaScript isolation was introduced via JS Module export/import. So if you still need to use JS interop do not pollute window object.

Update: .NET 5 was released and this feature works unchanged.

Also found a cool Nuget package which can do some convenient JS tricks for you e.g.: focusing previously active element without having a @ref to it. See docs here.

Solution 3

I was able to accomplish this by entering the JavaScript directly in the Host.chtml file (you can also add a .js file like the walkthrough suggests):

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

Next, in an extension file, I've added the extension (NOTE: I renamed Focus to FocusAsync because of naming standards:

public static async Task FocusAsync(this ElementReference elementRef, IJSRuntime jsRuntime)
{
    await jsRuntime.InvokeVoidAsync(
        "exampleJsFunctions.focusElement", elementRef);
}

Then in the razor page (or component), inject the IJSRuntime, Add an ElementReference and tie it to the element you want to focus (Note: Method names were changed to abide to naming standards):

@inject IJSRuntime JSRuntime
@using JsInteropClasses

<input @ref="username" />
<button @onclick="SetFocusAsync">Set focus on username</button>

@code {
    private ElementReference username;

    public async Task SetFocusAsync()
    {
        await username.FocusAsync(JSRuntime);
    }
}

Solution 4

There are a couple of ways to set focus on an element the Blazor native way. Here's one:

Create a class that derives from the InputBase<string> which is the base class of InputText with the same functionality of InputText. In short, copy the code of InputText to your newly created class, and add the necessary functionality. Here's the new class: TextBox.cs

public class TextBox : InputBase<string>
    {

        private ElementReference InputRef;
        protected override void BuildRenderTree(RenderTreeBuilder builder)
    {

            builder.OpenElement(0, "input");
    builder.AddMultipleAttributes(1, AdditionalAttributes);
    builder.AddAttribute(2, "class", CssClass);
    builder.AddAttribute(3, "value", BindConverter.FormatValue(CurrentValue));
    builder.AddAttribute(4, "onchange", EventCallback.Factory.CreateBinder<string>
        (this, __value => CurrentValueAsString = __value, CurrentValueAsString));
    builder.AddElementReferenceCapture(5, (value) => {
                InputRef = value; } );


            builder.CloseElement();


    }
        [Inject] IJSRuntime JSRuntime { get; set; }

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

        protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage)
        {
        result = value;
        validationErrorMessage = null;
        return true;
        }
        }

   } 

Place this script at the bottom of the _Host.cshtml file, just below

<script src="_framework/blazor.server.js"></script>

<script>

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

Things to note: 1. Define an ElementReference variable to hold reference to the input element. 2. In the BuildRenderTree method I've added code to capture a reference to the input element 3. Call the focusElement JavaScript function from the OnAfterRenderAsync method. This is performed only once. Note that I cannot use the OnInitializedAsync method which is executed only once, but the ElementReference variable may contain null. 4. Note that you cannot run any of the forms components without EditForm...

IMPORTANT: Pressing Ctrl+F5, when your browser is in a minimized state may interfere with seeing the cursor in the text element.

Code for usage:

<EditForm  Model="@employee" OnValidSubmit="@HandleValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <TextBox @bind-Value="@employee.Name"/>

    <button type="submit">Submit</button>
</EditForm>

@code {
    private Employee employee = new Employee();

    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }

    public class Employee
    {
        public int ID { get; set; } = 1;
        public string Name { get; set; } = "Nancy";
    }
} 

Solution 5

For .NET 6:

In your code, create an InputText variable, either in @code, or behind code:

private InputText inputTextForFocus;

In the Blazor InputText component, reference that variable:

<InputText @ref=inputTextForFocus>

Then, in your code, at the appropriate place, you can access the underlying Element of the InputText and call FocusAsync(). Note Element can be null.

For instance, to set focus on startup:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
      if (inputTextForFocus.Element != null)
           await inputTextForFocus.Element.Value.FocusAsync();
}

Credit where credit is due: https://www.youtube.com/watch?v=9Q7cXdylU7k

Share:
18,065
Uwe Keim
Author by

Uwe Keim

German developer. Some of my apps: SharePoint Systemhaus Göppingen (zwischen Stuttgart und Ulm) Eigene Homepage erstellen Test Management Software Windows 10 Ereignisanzeige Very proud father of Felix (2012) and Ina (2014). Loves running, climbing and Indian food. Code Project member #234.

Updated on June 29, 2022

Comments

  • Uwe Keim
    Uwe Keim almost 2 years

    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?

  • mfluehr
    mfluehr over 3 years
    There's no such thing as a "CSS class." I think you just mean "element class." Element classes can be used in either CSS or JavaScript.
  • Uwe Keim
    Uwe Keim over 3 years
    It seems that you are the owner of the NuGet package you mention. Correct?
  • Mort
    Mort over 2 years
    InputText isn't an ElementReference, so this implementation won't work on that.
  • John Goudy
    John Goudy about 2 years
    I had to add if (inputTextForFocus != null) since on the first call to OnAfterRenderAsync it was null, but on later calls it wasn't.
  • TheGeneral
    TheGeneral about 2 years
    Please state your affiliation with this nuget package meta.stackoverflow.com/questions/308002/…