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
Possibly redundant now .net 5 is out, but if you don't want to hard code an element's Id or derive your own input class, an easy way to achieve this is to just add a CSS class to the element, and then find and set focus to that using getElementsByClassName.
Create a script to contain the helper:
var JSHelpers = JSHelpers || {};
JSHelpers.setFocusByCSSClass = function () {
var elems = document.getElementsByClassName("autofocus");
if (elems.length == 0)
return;
elems[0].focus();
};
Create a shared 'AutofocusByCSS' component to handle calling the JS at the right time:
@inject IJSRuntime JSRuntime
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) JSRuntime.InvokeVoidAsync("JSHelpers.setFocusByCSSClass");
}
}
Then in your page:
Works on anything that boils down to a standard HTML element and makes it easier to change the autofocus target by changing the class name output.