Live Chat Icon For mobile
Live Chat Icon

How do you set the focus to an InputText element?

We can focus an InputText Blazor element not directly but by using JavaScript in Blazor. We can set an ID for the InputText and then pass it to JavaScript using interop by method InvokeVoidAsync. In the JavaScript function, use the focus DOM input method for focusing the input element with the received ID from Blazor.

Refer to the following code snippet.

function focusInput(id) {

Refer the script file in the HTML page

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

@page "/"

@inject IJSRuntime jsRuntime

<EditForm Model="@inputText">
    <InputText id="@InputID" @bind-Value="inputText.TextValue">You can enter some text...</InputText>

<br />
<br />

<button @onclick="Focus">FOCUS!!!</button>

@code {

    public string InputID = "input-id";
    public string Output = "";

    public class InputTextClass
        public string TextValue = "Some Random Text";

    public InputTextClass inputText = new InputTextClass();

    public async Task Focus()
        await jsRuntime.InvokeVoidAsync("focusInput", InputID);

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.