I am creating a Blazor PWA application using Visual Studio 2019. I use javascript to set focus to InputText fields during startup and certain key events.
function focusInput(id){
document.getElementById(id).focus();
var tb = document.querySelector("#" + id);
if (tb.select) {
tb.select();
}
}
and call it in my code behind like this
private string inputID = "user-id";
protected async override Task OnAfterRenderAsync(bool firstRender)
{
await jsInterop.InvokeVoidAsync("focusInput", inputID);
}
This is the razor page
<EditForm Model="@login" class="card card-body mt-2">
<div class="form-group row">
<label for="userid" class="col-sm-2 col-form-label">User ID</label>
<InputText id="@inputID" class="form-control" @bind-Value="@login.UserID" @onkeyup="(KeyboardEventArgs e) => KeyUpUserIDAsync(e)"/>
</div>
<div class="form-group row">
<label for="message" class="col-sm-2 col-form-label">Message</label>
<InputTextArea id="textarea-message" class="form-control" @bind-Value="@errorMessage" />
</div>
</EditForm>
It works great except when I run it and load the first page which is the Login Page. Instead of getting focus in the field, the focus instead stays in the URL bar. If I refresh the page the InputeText gets focus. Note that all the other pages I navigate to after logging in do not have this problem. Just the initial page. I wrote to the console to make sure it was being called and it was. I also tried using autofocus attribute but it does not work either.