Search code examples
htmlblazormauionkeyup

How to get inputs from a mobile virtual keyboard in MAUI?


I would like to be able to know which key is pressed on a mobile keypad, but @onkeyup only triggers when the mobile equivalent of enter is pressed, with KeyboardEventArgs.Code equaling an empty string. I have tried looking up any information on a mobile equivalent of KeyboardEventArgs, or even just why @onkeyup doesn't trigger when every key is pressed despite onkeyup="this.value = this.value.toUpperCase()" working on each key stroke just fine. I'm frankly bamboozled.

HTML code that works:

<input @bind="StringInput" id="textInput" onkeyup="this.value = this.value.toUpperCase()" />

Blazor code I've tried:

<input @bind="StringInput" id="textInput" @onkeyup="InputReceivedInput" />

@code {
    private string StringInput = string.Empty;

    private void InputReceivedInput(KeyboardEventArgs Args)
    {
        if (Args.Code == "Enter" || Args.Code == "NumpadEnter")
        {
            //call another function
        }
        else
        {
            StringInput = StringInput.ToUpper();
        }
    }
}

Second Attempt (only changed HTML portion):

<input @bind="StringInput" id="textInput" onkeyup="@InputReceivedInput" />

Solution

  • I tested the code you provided, and the onkeyup method has the issue that it cannot update the data after pressing a button on the keyboard. For this issue, you can report it on the GitHub issue.

    In addition, I found another way to achieve this: using the @bind:get and @bind:set. For more information, you can check this document about ASP.NET Core Blazor data binding.

    <input @bind:event="oninput" @bind:get="StringInput" @bind:set="OnInput" id="textInput" />
    
    <p>
        <code>StringInput</code>: @StringInput
    </p>
    
    <input @bind="StringInput" id="textInput" onkeyup="this.value = this.value.toUpperCase()" />
    
    @code {
        private string StringInput = string.Empty;
    
        private void OnInput(string value)
        {
            var newValue = value ?? string.Empty;
    
            StringInput = newValue.ToUpper();
        }
    }