How to set the focus to an InputText element?

前端 未结 5 533
灰色年华
灰色年华 2021-01-12 17:21

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

5条回答
  •  自闭症患者
    2021-01-12 17:55

    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.

提交回复
热议问题