Unchecking an available item observable in Knockout.js when clicking on a selected item

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>

Answer №1

It's been a while since I last worked with Knockout.js, but it seems like the issue you're facing is related to how the remove() method is handling user removal from the SelectedUsers observable. You should be removing user names from the selectedUserNames observable instead.

The way your binding is configured, you're subscribing to changes in the selectedUserNames observable and updating the SelectedUsers observable within that subscription. This means that the subscription wasn't triggering when users were removed from the SelectedUsers observable, which explains why the corresponding user wasn't getting unchecked when a username was removed.

To address this problem, modify the following method:

self.remove = function(e) {
  self.SelectedUsers.remove(e);
}

to this revised version:

self.remove = function(e) {
  self.selectedUserNames.remove(e.userName());
}

Below is an updated example incorporating the changes into your existing code:

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([]);
  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.selectedUserNames.remove(e.userName());
  }
}
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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to sort the list items when utilizing the load() function

I have multiple li elements within a ul and I am using the following code to sort them in ascending order based on the data-percentage attribute: $(function() { $(".alll li").sort(sort_li).appendTo('.alll'); function sort_li(a, b) { re ...

The installation of AngularJS libraries via npm was unsuccessful

After installing mean.io and running sudo npm install, I followed the commands in sequence: sudo npm install -g meanio mean init yourNewApp cd yourNewApp sudo npm install -g bower sudo npm install The process was supposed to download and install AngularJ ...

The Autocomplete component from MUI is alerting me to provide a unique key for every child element being passed

I am currently using the Autocomplete component from MUI and encountering an issue with a warning that says: Warning: Each child in a list should have a unique "key" prop. Although I've added keys to both renderOption and renderTags, the wa ...

What is the method for retrieving an attribute's value from an object that does not have key-value pairs?

My current project involves working with dynamoose and running a query that produces the following output: [ Document { cost: 100 }, lastKey: undefined, count: 1, queriedCount: undefined, timesQueried: 1 ] When I use typeof(output), it returns O ...

The variable returned by ajax on the next page is not present upon arrival

I am sending a variable via ajax from index.php to home.php. If the operation is successful, I return the variable (userID). Otherwise, I return "Noone". When I check index.php, I see an alert with "user:1" along with some other unwanted content from the p ...

Attempting to remove certain selected elements by using jQuery

Struggling to grasp how to delete an element using jQuery. Currently working on a prototype shopping list application where adding items is smooth sailing, but removing checked items has become quite the challenge. Any insights or guidance? jQuery(docume ...

Adjust the input values based on the child elements within the main container

Here is a series of DIVs with unique IDs: <div id="2988"> <div class="site">YaHoot.com</div> <div class="logo">/images/yahootLogo.jpg</div> //[and so on] <input type="button" value="YaHoot" onclick="javascript: ...

custom dialog box appears using ajax after successful action

Recently, I created a custom dialog/modal box with the following code: <div id="customdialog" class="modal"> <div class="modal__overlay"></div> <div class="modal__content"> <h2><strong>Hello</strong&g ...

Using JQuery's ajax() method within a for loop

I'm currently working on implementing default edit mode in a Razor view. Everything seems to be functioning properly except for the filling function for the dropdown list. As part of my task, I need to populate the state dropdown list based on the cur ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

ng-include does not incorporate a partial view

I am facing an issue with ng-include as this code is not functioning properly and I'm unable to identify the error. <select name="select" id="select" class='input-large' ng-model="selectedbien"> ...

Tips for disabling viewport resizer while accessing the Console panel in Chrome using Control+Shift+J

Currently, I am utilizing the viewport resizer in Chrome to preview how my code appears on various devices. However, I have encountered an issue - whenever I try to access the console using ctrl + shift + j, the viewport resizer opens instead. You can obs ...

Removing Multiple Object Properties in React: A Step-by-Step Guide

Is there a way in React to remove multiple object properties with just one line of code? I am familiar with the delete command: delete obj.property, but I have multiple object properties that need to be deleted and it would be more convenient to do this i ...

Dynamic Form Layout with Angulajs' Adaptive Data

As a developer, I have created a form using a directive and I am supplying the layout data from my controller. TheController.js [{ "type":"selectbox", "name":"name_one", "label":"Name One" }] This information is then sent to my form_directive which handl ...

Efficiently uploading images with AJAX when submitting a form

I am attempting to upload an image along with other variables in a form submission, and then execute my PHP code to store the image in the user's profile_picture table. I want the image upload to be integrated within the same form used for saving dat ...

Guide to profiling resources in Node.js applications

When developing Node.js applications, it's important to keep track of how your code is performing in terms of memory and IO. By monitoring these metrics, you can identify which parts of your code are causing delays or consuming excessive resources. Th ...

Error: The value provided is not compatible with the HTMLInputElement interface

I am currently attempting to submit a form using jQuery-ajax, but I keep encountering the following error when trying to submit the form on click: TypeError: Value does not implement interface HTMLInputElement Here is the JavaScript code I am using: ...

When attempting to pass a variable from Ajax to PHP, the function "isset($_POST[])" may not function as expected

While attempting to capture the AJAX post in my PHP code, I encountered a problem. Here is what I am trying to achieve: whenever there is a change in the value of select2, I want to retrieve that result and send it to my PHP script for use in a database q ...

Have I got it all wrong with the way Controllers communicate with Services and how I conduct unit testing?

Currently, I am in the process of developing an AngularJS application and I want to ensure it follows best practices. When making external API calls using either $resource or $http, I always do this within a separate Service or Factory. However, I am unsur ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...