Reputation: 93
In KnockoutJS, two way binding is not working for inputs in a foreach loop. Modifying the text input does not modify the span value. This only seems to be an issue when using a foreach loop.
<html>
<body>
<table>
<tbody data-bind="foreach: users">
<tr>
<td><span data-bind="text: firstName"></span></td>
<td><input data-bind="value: firstName" type="text"></span></td>
<td><span data-bind="text: lastName"></span></td>
<td><input data-bind="value: lastName" type="text"></td>
</tr>
</tbody>
</table>
<script src="js/libs/knockout-3.2.0.js"></script>
<script>
function User(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
function UserListViewModel() {
var self = this;
self.users = ko.observableArray([
new User("Joe", "Schmoe"),
new User("James", "Ronald")
]);
}
ko.applyBindings(new UserListViewModel());
</script>
</body>
</html>
Upvotes: 2
Views: 711
Reputation: 4236
Just make your User
properties observable
:
function User(firstName, lastName) {
this.firstName = ko.observable(firstName);
this.lastName = ko.observable(lastName);
}
observables are special JavaScript objects that can notify subscribers about changes, and can automatically detect dependencies.
Upvotes: 1