I have:
<input onkeypress="@Foo" />
and:
@functions
{
void Foo(UIKeyboardEventArgs e)
{
}
}
How do I pass, or otherwise retrieve, the value of the input in the handler method?
The value of an input element is updated in the wrapper with the change events of elements in Blazor. To get the current value for each character input, you must use the oninput event of the input element. This can be achieved by binding the oninput event (native event) using the @bind:event=“oninput“.
The input element value is updated by the @bind event in Blazor. To get the current input value, use the oninput native event of the input element and get the current input value.
Use the val() : $("#my_field"). keydown (function (e) { alert ($(this). val()); });
By default, binding applies to the element's onchange event. If the user updates the value of the text box's entry to 123.45 and changes the focus, the element's value is reverted to 123 when onchange fires.
Unfortunately, you need oninput event to update the bound variable.
@value
<input type="text" @bind="@value" @oninput="@(ui => { value = (string) ui.Value);})" />
@functions {
string value;
}
For people searching about this, you can implement this with .net core 3.1 to handle on keypress event on Blazor.
<input value="@stringValue" @oninput="(EventArgs) => {SetValue(EventArgs.Value.ToString()); DoSomethingElse();}"/>
@code {
string stringValue = "";
private void SetValue(string Value)
{
stringValue = int.Parse(Value);
}
}
"KeyboardEvent events just indicate what interaction the user had with a key on the keyboard at a low level". In order to access the text input, you should use the input event or change event instead. In Blazor, right now the input event is wrapped by the change event; that is, your code can access new values only after the input element has lost focus. What you should do, however, is define a property which is bound to the input element and can be accessed in your code for retrieval purposes:
protected string MyInput {get; set;}
<input type="text" bind="@MyInput" />
The above binding is internally based on the change event, not the input event (again, right now it is not possible in Blazor)
You can use the 'oninput' event instead. This event is called every time the value of the Input-element changes. It takes one parameter which is a UIChangeEventArgs that contains a Value property with the Input-elements current value. E.g.
<input type="text" oninput="@((ui) => { Foo((string)ui.Value);})"/>
@function {
void Foo(string s)
{
//do stuff
}
}
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