Knockout event binding for input keypress causes weird behavior

Pejman picture Pejman · Apr 20, 2013 · Viewed 16.6k times · Source

Long story short, I want to enable users to hit enter on an input element and certain method in my viewmodel be called. Here is my html input:

<input id="searchBox" class="input-xxlarge" type="text" data-bind="value: searchText, valueUpdate: 'afterkeydown', event: { keypress: $parent.searchKeyboardCmd}">

and here is my method in vm:

searchKeyboardCmd = function (data, event) { if (event.keyCode == 13) searchCmd(); };

everything works fine and searchCmd is called when I hit enter on input, but the problem is that I can type nothing in input, i.e. everything I type into input is ignored. Thank you in advance for your help.

Answer

Andrejs Kuzmins picture Andrejs Kuzmins · Apr 20, 2013

According to KO docs you have to return true from your event handler if you want the default action proceed.

searchKeyboardCmd = function (data, event) {
    if (event.keyCode == 13) searchCmd();
    return true;
};