Reputation: 31565
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?
Upvotes: 33
Views: 37182
Reputation: 51645
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
To people that are looking for oninput
with 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" />
Upvotes: 71
Reputation: 450
Following the recommendations from this thread, I used both oninput and onchange, and got my textbox to work even inside a table where each record is represented as r. It goes like this:
<td><input type="number" value="@r.SequenceNbr" @oninput="(e) => NewSeqNbr = e.Value.ToString()" @onchange="() => ChangeSeqNbr(r.Id)" ></td>
And in the code, I have:
public string NewSeqNbr { get; set; }
private async Task ChangeSeqNbr(int recId)
{
.....
// NewSeqNbr is available here
.....
}
Upvotes: 1
Reputation: 3636
In .NET 5 Blazor, @oninput
seems to work fine directly on InputText
:
<InputText @oninput="(e) => StringProp = e.Value.ToString()"></InputText>
So, thankfully, enabling the Submit button on forms right when they become touched is also possible without custom components. E.g.:
<InputText @oninput="() => untouched = false"></InputText>
...
<button type="submit" disabled="@untouched">Submit</button>
Upvotes: 5
Reputation: 23680
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
Upvotes: 3