I was trying the todo-list example from Microsoft: https://docs.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;
}
}
}
}
Blazor does not have support to manipulate DOM elements directly, but we can still achieve it by using JavaScript interop. By creating a reference to an element, we can send it as a parameter to the JavaScript method via interop.
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
To detect a browser keypress event, set the @onkeypress event to the corresponding element. For hotkey functions, you can use the event arguments to check whether the Ctrl, Shift, or Alt key is pressed. For more information on this topic, check this documentation.
An event callback function is a function in a script that Monitoring Scripting Client calls in response to an event. In your event callback functions, provide code to generate statistics from the data in events. Typically, the following types of statistics can be generated from the data in events: Counter statistics.
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")
{
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With