When you click on the elements in the top list, a selection is made. If you click on the elements in the bottom list, it will be removed from the list. However, the checkbox in the top list is not being unchecked. How can this issue be resolved?
function User(data) {
this.userName = ko.observable(data.userName);
this.selected = ko.observable(data.selected);
}
var dataSource = [
new User({
userName: "test1",
selected: false
}),
new User({
userName: "test2",
selected: false
})
];
function UsersViewModel() {
var self = this;
//initial data may have two IEnumerables
self.AllUsers = ko.observableArray(dataSource);
self.SelectedUsers = ko.observableArray([]);
self.selectedUserNames = ko.observableArray([]);
remove: function myfunction() {
SelectedUsers().remove(this);
}
self.selectedUserNames.subscribe(function(newValue) {
var newSelectedUserNames = newValue;
var newSelectedUsers = [];
ko.utils.arrayForEach(newSelectedUserNames, function(userName) {
var selectedUser = ko.utils.arrayFirst(self.AllUsers(), function(user) {
return (user.userName() === userName);
});
newSelectedUsers.push(selectedUser);
});
self.SelectedUsers(newSelectedUsers);
});
self.remove = function(e) {
self.SelectedUsers.remove(e);
}
}
ko.applyBindings(new UsersViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Available
<ul data-bind="foreach: AllUsers, visible: AllUsers().length > 0">
<li>
<!--<div data-bind="click: $parent.SelectedUser">-->
<input type="checkbox" name="checkedUser" data-bind="value: userName, checked: $root.selectedUserNames" />
<span data-bind="text: userName"></span>
<!--</div>-->
</li>
</ul>
<br />Selected
<ul data-bind="foreach: SelectedUsers, visible: SelectedUsers().length > 0">
<li data-bind="click: $parent.remove">
<span data-bind="text: userName"></span>
</li>
</ul>