knockout.js input box event change – passes old value

Update: For newer versions of knockout, you can replace the value binding with textInput, which handles many edge cases not covered by valueUpdate.


No, this is not the right way to do things.

You’re getting the old value because saved_value doesn’t get updated until the textbox loses focus.

If you want to push the new value in as the user types, using the valueUpdate option of the input binding:

<input data-bind="event: { change: value_changed }, value: saved_value, valueUpdate: 'afterkeydown'" />

The valueUpdate option takes an event name (e.g. ‘keyup’). When that event fires, your saved_value will be updated.


Now let me propose an alternate solution.

Still do the valueUpdate binding like I showed above, but instead of listening for the changed event, just subscribe to the observable:

<input data-bind="textInput: saved_value" />

Then in JS:

var viewModel = {
    saved_value: ko.observable("1"),
};
viewModel.saved_value.subscribe(function (newValue) {
   alert(data.saved_value());
});
ko.applyBindings(viewModel);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)