I have Blazor page where I want to make a to-do list that updates either when a button is pressed, or when the user hits enter. I want "enter" and the button to do the same action (adding what I've typed into the box to my todo list. Right now 'enter' works, but I have to hit enter twice. I only want to have to hit it once. The button works as intended.
<input placeholder="Text Here" type="text" @onkeydown="@Enter" @bind="newTodo" />
<button @onclick="AddTodo">Add todo</button>
@code {
private string newTodo;
private IList<TodoItem> todos = new List<TodoItem>();
private void AddTodo()
{
// Todo: Add the todo
if (!string.IsNullOrWhiteSpace(newTodo))
{
todos.Add(new TodoItem { Title = newTodo });
newTodo = string.Empty;
}
}
public void Enter(KeyboardEventArgs e)
{
if (e.Key == "Enter")
{
// Todo: Add the todo
if (!string.IsNullOrWhiteSpace(newTodo))
{
todos.Add(new TodoItem { Title = newTodo });
newTodo = string.Empty;
}
}
}
}
<ul>
@foreach (var todo in todos)
{
<li>
<input type="checkbox" @bind="todo.IsDone" />
<input @bind="todo.Title" />
</li>
}
</ul>
I've tried removing @onkeydown="@Enter", but then obviously nothing fires but the button
and
if (e.Key == "Enter")
{
AddTodo()
}
I was hoping the later would skip some step that is requiring an extra input, but it made me double paste the code there.
Use the standard Blazor form controls and it will work as you expect.
Here's a demo page: