Why do I have to double click enter on Blazor?

38 views Asked by At

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.

1

There are 1 answers

0
MrC aka Shaun Curtis On

Use the standard Blazor form controls and it will work as you expect.

Here's a demo page:

@page "/"

<PageTitle>Home</PageTitle>

<h1>Demo ToDo</h1>

<EditForm Model="_model" OnValidSubmit="HandleValidSubmit">

    <div class="mb-3">
        <label>ToDo</label>
        <InputText class="form-control" @bind-Value="_model.Value" />
    </div>

    <div class="mb-3 text-end">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>

</EditForm>

<div class="bg-dark text-white m-2 p-2">
    <pre>Value : @_model.Value</pre>
    <pre>Message : @_message</pre>
</div>

@code{
    private ToDo _model = new();
    private string? _message;

    private async Task HandleValidSubmit()
    {
        // Fake some async activity
        await Task.Delay(100);
        _message = $"Submitted at {DateTime.Now.ToLongTimeString()}";
    }

    public class ToDo
    {
        public Guid Uid { get; set; } = Guid.NewGuid();
        public string? Value { get; set; }
    }
}