I have the following code:
<input [email protected] onkeypress="@KeyPress" />
@functions {
public string Value { get; set; }
void KeyPress(UIKeyboardEventArgs e)
{
if (e.Key == "Enter")
{
Console.WriteLine(this.Value);
}
}
}
When I write some text in the input field (for example test1
) and click enter I get empty text written on the console. When I add some more text (like test2
) and again click enter I get just test1
(the previous value before the enter click) on the console:
I believe this is expected. The bind is handled using the onchange
event, which isn't triggered until after onkeypress
is fired.
@danroth27 How to get input value in the onkeyup
event? I can't get input value from UIKeyboardEventArgs
event data.
@doggy8088 look here for general idea:
https://blazor.net/docs/javascript-interop.html#capture-references-to-elements
This example uses element.focus()
. You have to create similar JS interoperability for element.value()
. Of course you have to return string
from this function. Look at example with prompt
function in the same doc.
It works using the onkeyup
event. The bound value from the input is set.
your code should look like:
<input [email protected] onkeyup="@KeyUp" />
@functions {
public string Value { get; set; }
void KeyUp(UIKeyboardEventArgs e)
{
if (e.Key == "Enter")
{
Console.WriteLine(this.Value);
}
}
}
Hello @sven5 is your syntax the current one for server side blazor preview 8?
I would have thought that this should work.
<input @bind="todo.Title" @onkeyup="AddTodoOnEnter" />
@code {
private void AddTodoOnEnter( UIKeyboardEventArgs eventArgs)
{
if (eventArgs.Key == "13" ) // fire on enter
{
AddTodo();
}
}
}
But neither @onkeyup="AddTodoOnEnter" nor @onkeyup="@AddTodoOnEnter" works. In firefox the DOM property for _blazorEvents_1: does not contain an onkeyup.
I also tried if (eventArgs.Key == "Enter")
but it did not make a difference.
So i just got this working. You may want to try the following:
<input @bind-value="MyValue" @bind-value:event="oninput" @onkeyup="DoTheThing" />
and then your @Code:
public string MyValue { get; set; }
private void DoTheThing( KeyboardEventArgs eventArgs)
{
if (eventArgs.Key == "Enter" ) // fire on enter
{
Console.WriteLine( "Done the thing: "+ MyValue);
}
}
Basically, the oninput bind-value:event saves the value of the input to the variable as you type, and then the Enter trigger allows you to process it when the user clicks return.
Most helpful comment
It works using the
onkeyup
event. The bound value from the input is set.your code should look like: