Aspnetcore: Input value always null on `onkeydown` or `onkeypress` event in Blazor

Created on 22 Dec 2018  路  8Comments  路  Source: dotnet/aspnetcore

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?

area-blazor question

All 8 comments

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.

@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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rbanks54 picture rbanks54  路  3Comments

ermithun picture ermithun  路  3Comments

markrendle picture markrendle  路  3Comments

Pixel-Lord picture Pixel-Lord  路  3Comments

FourLeafClover picture FourLeafClover  路  3Comments