Input value always null on onkeydown or onkeypress event but have value on onclick event in Blazor.
Here is my code:
<input onkeydown="@CheckInput" placeholder="Write To Do" bind="@NewToDo" />
<button onclick="@AddToDo">Add todo</button>
<br />
<span class="text-danger">@errorMessage</span>
@functions {
List<TodoItem> todos = new List<TodoItem>();
private string NewToDo { get; set; }
private string errorMessage;
private void CheckInput()
{
Console.WriteLine(NewToDo); // Strangely input value always null here.
}
private void AddToDo()
{
if (!string.IsNullOrWhiteSpace(NewToDo)) // Here value is getting as expected
{
errorMessage = null;
todos.Add(new TodoItem() { Title = NewToDo, IsDone = false });
NewToDo = null;
}
else
{
errorMessage = "Please enter a To do item!";
}
}
}
Why I am getting input field value always null on onkeydown or onkeypress while getting the value on onclick?
Try
onkeydown="@((__value) => NewToDo = __value)"
The bind property raises an OnChange event. Now, the OnChange event is raised only after the element loses focus. So while you type in your input field, the NewToDo value will remain the same. Try clicking somewhere else and then typing again, you will get your console message right.
@Mirch You are correct! But is there any option to get the current value while typing?
@Mirch You are correct! But is there any option to get the current value while typing?
What's your use case here? I assume something like a real time search, but maybe there's a workaround for whatever you are trying to accomplish.
@Mirch My requirement is Getting the current value while typing(on each keypress) on input field like JavaScript/jQuery.
Read my comment here: https://github.com/aspnet/AspNetCore/issues/6052#issuecomment-450139089
@Andrzej-W Thank you! Surely I shall take a look into it.
Thanks for contacting us. We believe that the question you've raised have been answered. If you still feel a need to continue the discussion, feel free to reopen it and add your comments.