What I want to do is update the variable value when the user press a key, but it only update the value on blur of the input.
The following code is not working.
<p>@increment</p>
<input
type="text"
@onchange="@((ChangeEventArgs e) =>
increment = e.Value.ToString())"
/>
@code {
string increment;
}
Using @bind
and @bind-value
also doesn't work.
I made a blazorfiddle with the example.
Who can I make the value of my variable to change when the a key is pressed?
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“.
Use input change event to get the changed value in onchange event argument. If you bind using the two-way bind to value property, it will automatically change the value into the value property.
In Blazor, there is no significant difference between using these two attributes. The @bind attribute is a shorthand of the @bind-value attribute and its delegate will trigger the ValueChanged event of the component.
You can use the bind attribute on any element to bind the value. In blazor, we'll have a property assigned some value in the functions and use the property in the HTML template. Let's get this done. So, when we run the app, the label tag will display “red” as a text in the label.
Quoting Data Binding docs:
<input @bind="CurrentValue"
@bind:event="oninput" />
Unlike
onchange
, which fires when the element loses focus,oninput
fires when the value of the text box changes.
You can achieve it without @bind
directive:
<input value="@CurrentValue"
@oninput="(e)=> CurrentValue = e.Value.ToString()"/>
InputText
& oninput
For people looking for oninput
on InputText
component the answer is full documented on InputText based on the input event doc:
Use the InputText component to create a custom component that uses the input event instead of the change event.
Shared/CustomInputText.razor
:
@inherits InputText
<input @attributes="AdditionalAttributes" class="@CssClass"
@bind="CurrentValueAsString" @bind:event="oninput" />
The
CustomInputText
component can be used anywhereInputText
is used:
<CustomInputText @bind-Value="exampleModel.Name" />
In case anyone wants to do this with the InputText
form component provided create your own component file, eg InputTextOnInput.razor
:
@inherits InputText
<input @attributes="AdditionalAttributes" class="@CssClass"
@bind="CurrentValueAsString" @bind:event="oninput" />
Then use it in your form like so:
<InputTextOnInput @bind-Value="@PropertyToUpdate " />
@code {
private string PropertyToUpdate { get; set; }
}
More details on the Blazor docs
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