dumbmatter
dumbmatter

Reputation: 9653

Updating an input whose value attribute is bound to an observable, after editing the input

Here is an example on jsFiddle.

I have some HTML with Knockout bindings to display a value x both as the value of an input and as text in a p tag.

<p data-bind="text: x"></p>
<p><input id="x" data-bind="attr: {value: x}"></p>
<button id="update">Update</button>

What I want this to do is take the value in the input when the Update button is pressed, round it to the nearest integer, and have it display this rounded value in both places. I tried this:

var vm = {
    x: ko.observable(1)
};

ko.applyBindings(vm);

$('#update').click(function () {
    vm.x(Math.round($('#x').val()));
});

Here's the jsFiddle link again.

When you load it, the initial value of 1 is displayed in both places. If you change the value in the input to 2 and click the "Update" button, then both places will display 2. Wonderful. This works for any integer.

Now try something that's not an integer. Enter 5.3 and press "Update". The p correctly updates to display 5, but the input still shows 5.3.

Some further investigation seems to indicate that Knockout is happy to update the input until I manually edit the value in the input, at which point it stops doing anything to the input. I can understand why this might be desirable in some cases to prevent user input from being overwritten... but it's not the behavior I want. How can I get it to update both displayed values when the view model is updated?

Upvotes: 0

Views: 226

Answers (1)

segFault
segFault

Reputation: 1228

If you change your fiddle to use data-bind="value: x" intead of data-bind="attr: {value: x}" it will work perfectly.

Upvotes: 2

Related Questions