blazorkeyboard-eventsblazor-webassembly

Blazor, how can I trigger the enter key event to action a button function?


I was trying the to-do list example from Microsoft.

I want to add a todo item, but instead of pressing the button with a mouse click I want to press the enter key. I'm not happy with using JS like in this solution: How to set the focus to an InputText element? I tried to trigger the method private void Enter(KeyboardEventArgs e) by this line of code:

<button @onclick="AddTodo" @onkeypress="@(e=>Enter(e)" tabindex="0"  >Add todo</button>

However, it didn't work.

    enter code here
    <input placeholder="Something todo" @bind="newTodo" />
    <button @onclick="AddTodo" @onkeypress="Enter" tabindex="0"  >Add todo</button>

    @code {
        private IList<TodoItem> todos = new List<TodoItem>();
        private string newTodo;
    
        private void AddTodo()
        {
            if (!string.IsNullOrWhiteSpace(newTodo))
            {
                todos.Add(new TodoItem { Title = newTodo });
                newTodo = string.Empty;
            }
        }
    
        //private void Enter(KeyboardEventArgs e)
            private void Enter()
        {
            //if (e.Key == "Enter")
            {
                if (!string.IsNullOrWhiteSpace(newTodo))
                {
                    todos.Add(new TodoItem { Title = newTodo });
                    newTodo = string.Empty;
                }
            }
        }
    }

Solution

  • onkeypress is fired only for character keys. onkeydown will fire for all keys pressed. I found some explanation of differences between all key events here

    Try it with onkeydown and it worked:

    <input type="text" @onkeydown="@Enter" />
    

    In the event handler you will have to do this (notice that I check for both Enter and NumpadEnter keys):

    public void Enter(KeyboardEventArgs e)
    {
        if (e.Code == "Enter" || e.Code == "NumpadEnter")
        {
             // ...
        }
    }