I was trying the todo-list example from Microsoft: https://learn.microsoft.com/en-us/aspnet/core/tutorials/build-a-blazor-app?view=aspnetcore-3.1
I want to add a todo item and 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? And I try 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>
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;
}
}
}
}