26 December 2024

How to set the focus to an Input element with Blazor?

If, like me, you’re wondering how to give focus to an element of the DOM in your interface, don’t look any further, here is the solution 😉 which is very simple! Simple when you have already done a little web / javascript My goal was to restore focus to an Input element when the user failed to fill in a field. Here is what it looks like:
Blazor Focus élement DOM input

Javascript interoperability

I love this term that sounds smart when you say it ^^. In short, you just need to add a small piece of Javascript code to your project and simply give focus to an element identified by a … id, of course.

 window.jsfunction = { focusElement: function (id) { const element = document.getElementById(id); element.focus(); } }

Save this code in a .JS file with the name of your choice. Then declare between the Header tags of your index page. For Blazor Webassembly applications it’s in the wwwwroot/index.html folder. For Blazor Server applications it’s in the _Host.cshtml file.

I don’t think I can teach you anything by telling you it’s like this:

 <script src="js/focus.js"></script>

What about the Blazor code?

Just add the interface IJSRuntime to your page .razor. As our code javascrpit returns nothing, it will then be enough to call it via InvokeVoidAsync :

@inject IJSRuntime js

<input Id="idPassWord" Type="password" @bind="_pass" />

<button @onclick="clickOK">Valider</button>

@code {
    private string _pass;

    private async void clickOK()
    {
        if (String.IsNullOrEmpty(_pass))
            await Focus("idPassWord");
        else
    {
            // your code
    }
    }

    public async Task Focus(string elementId)
    {
        await js.InvokeVoidAsync("jsfunction.focusElement", elementId);
    }
}

Once again, you will have understood it, it’s super simple!

Leave a Reply