I am using Blazor WebAssmebly. I have an input box and I simply want to reset it to no text after the user types in text and hits the Enter key:
<input id="txtWord" name="txtWord" placeholder="Enter your text" @onchange="@onChange" @onkeyup="@Enter" />
private void onChange(Microsoft.AspNetCore.Components.ChangeEventArgs args)
{
value = (string)args.Value;
}
public void Enter(KeyboardEventArgs e)
{
if (e.Code == "Enter" || e.Code == "NumpadEnter")
{
if (value.Trim() != "")
{
doSomething();
}
}
}
So I set the variable 'value' to the input text, but then I want to clear the text box. How do I do that?
It looks like as if you're not binding your input to the value
variable. Your code should be something like this:
<input id="txtWord" name="txtWord" placeholder="Enter your text"
value ="@value" @onchange="onChange" @onkeyup="Enter" />
@code
{
private string value;
}
Note that by adding the value attribute to the input element I create a two-way databinding, from the variable to the control, and from the control to the variable. When you use the @onchange
directive, you create a one-way data binding.
In order to reset the input element, you can do the following:
if (value.Trim() != "")
{
// I guess it is here that you want to reset the input
// element. Assigning empty string to the `value` variable
// will cause the control to re-render with the new value;
// that is empty string...
value = "";
doSomething();
}