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