The issue with checkboxes in datatables causing incorrect array output

Trying to integrate a checkbox into my datatables for row selection and storing selected information in array for further processing.

The datatable supports pagination and variable page lengths, but encounters an issue with the following scenario:

Scenario:

Datatables set with 10 items per page. Select multiple rows from the initial 10. Change page length to 25, select more rows which are added to the array. If unchecking the initially selected rows, they are removed and then re-added to the array if still checked. This behavior only applies to previously selected rows before changing the page length.

Example:

Array page size 10, x = selected

[(x)test1, (x)test2, test3, .., test10]

selectedArray
[test1, test2]

Page size 10 -> 25

[(x)test1, (x)test2, test3, .., (x)test11, (x)test12, .., test25]

selectedArray
[test1, test2, test11, test12]

Unselect row from first 10

[test1, (x)test2, test3, .., (x)test11, (x)test12, .., test25]

selectedArray
[test2, test11, test12, test1]

Select row from first 10 again

[(x)test1, (x)test2, test3, .., (x)test11, (x)test12, .., test25]

selectedArray
[test2, test11, test12, test1]

Test3 will not appear in the list after changing to page size 25.

Typescript Component

this.dtOptions = {
 pagingType: 'full_numbers',
 searching: true,
 pageLength: 10,
 processing:true,
 responsive:true,
 order: [[ 1, "asc" ]],
 lengthChange: true,
 lengthMenu: [[10, 15, 20, 25, 50], [10, 15, 20, 50]],
 autoWidth: false,
 stateSave: true,
 stateDuration: 48,
 retrieve: true,
 paging: true,
 columns: [
          { 'data': 'null', defaultContent: ''},
          { 'data': 'name'},
          { 'data': 'version' },
          { 'data': 'newVersion' },
          { 'data': 'null' }
],
columnDefs: [
{
   targets : 0, render:function() {
    return '<input type="checkbox" class="check" data-object-id="">';
   }
 }
],
rowCallback: (row: Node, data: object, index: number) => {
 $('td', row).unbind('click');
 $('td:first input',row).bind('click', () => { // CHECKBOX
  this.selectPackage(data['name'])
  if(this.isSelected(data['name'])){
    $('input[type="checkbox"]', row).prop('checked');
   }
  })
 return row;
 },
ajax: ....
}

isSelected(name) {
    return this.getIndexFrom(name) >= 0;
}

getIndexFrom(name) {
    return this.selectedPackages.indexOf(name);
}

selectPackage(name) {
 const index = this.selectedPackages.indexOf(name);
  if (index >= 0) {
   this.selectedPackages.splice(index, 1);
 } else {
   this.selectedPackages.push(name);
 }
   this.selectAll = false;
}

Row Structure

<tr role="row" class="even">
 <td>
   <input type="checkbox" class="check" data-object-id="">
 </td>
 <td class="sorting_1">
   AA_test
 </td>
 <td></td>
 <td>NaN</td>
 <td></td>
</tr>

Looking for a solution or suggestions on how to address this issue.

Answer №1

After some investigation, I discovered that my approach to binding was flawed. Here is the corrected method I used:

rowEnhancer: (node: Element, data: Record<string, any>, position: number) => {
          const check =  $('td:first input', node);
          check.prop('checked', this.isSelected(data['name']));
          check.unbind();
          check.click(() => this.chooseSelection(data['name']));
          return node;
}

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

Is there a clash with another code causing issues in troubleshooting a straightforward jQuery function?

jQuery(document).ready(function() { jQuery("#bfCaptchaEntry").on("click", function(){ jQuery("#bfCaptchaEntry").css("background-color", "#FFFFFF"); }); jQuery("#bfCaptchaEntry").on("blur", function(){ jQuery("#b ...

Can you provide details about the launch configuration for pwa-node in VSCode?

When setting up npm debugging in VSCode, I couldn't help but notice that the default launch configuration is labeled as "pwa-node" instead of just "node". Here's what the "Launch via NPM" configuration looks like: https://i.sstatic.net/EQ5c5.pn ...

Sending jQuery events from an aspx page to an ascx control

Yesterday, I began utilizing ascx and started breaking down my "dynamic" default.aspx page into smaller segments. In default.aspx, there is a significant amount of JavaScript/jquery code responsible for managing various events. After moving some html code ...

Exporting custom type definitions using a node module

In my project, I have a module named module_core with a specific directory structure as shown below: /src /company /webservices /service-one ... /service-two ... /service-new // my service i ...

What is the best way to access an Ajax response outside of its function using JQuery?

Just starting out with JQuery and wondering how to utilize the Ajax response ( HTTP GET ) outside of the function in my code snippet below: $.ajax ({ type: "GET", url: "/api", success: success, error: error ...

Challenge with sharing an array from a different component in Angular using @Input()

Recently, I started learning Angular and decided to create a basic blog application. While trying to retrieve a property from another component using the @Input() decorator, I encountered an issue specifically related to arrays. In a post-list-item compone ...

What is the best way to transfer text from one ListBox to another ListBox and retrieve the value on the server side?

I am currently working on a project where I have implemented functionality to move items from one listbox to another using jQuery. The code for this part is already in place and functioning properly. Now, my next task is to retrieve the values of the moved ...

What is the best method to activate a JavaScript function after 1 minute of user inactivity?

I need to set up a web page where a JavaScript function is activated after 1 minute of user inactivity. The page primarily features the <form> component. What's the best way to implement this type of function? ...

Utilizing Typescript and sinon to mock the functionalities of jsonwebtoken

Looking for help with mocking the function verify in Typescript's jsonwebtoken library. I've installed typescript, jsonwebtoken, sinon, mocha, and chai along with their corresponding types. However, when trying to stub the function, an error occu ...

Acquiring @ViewChild in pug - A step-by-step guide

Developing an Angular2 application using pug has presented a challenge. While the HTML version of my template works fine, the Pug version is not cooperating. Can someone spot what I might be missing? // HTML <div #main> <h1>Test Html</h ...

Tips for implementing a cascading dropdown feature in Angular 7 Reactive Formarray: Ensuring saved data loads correctly in the UI form

I recently found a helpful guide on stackoverflow related to creating cascading dropdowns in an Angular reactive FormArray, you can check it out here After following the instructions, I managed to achieve my desired outcome. However, I now face a new chal ...

Tips for adding classes to both parent and child elements in dynamically loaded data via an ajax request

I am facing a challenge with jQuery as a beginner. I have been struggling for the past week to load data from a JSON array using an ajax call. I'm also using a swipe plugin to swipe and display all images on the same div, but I'm unsure of how to ...

Guide to dynamically altering the header logo as you scroll further

I'm attempting to dynamically change the logo in my header based on how far I've scrolled down the page. While I have experimented with libraries like Midnight.js, I specifically need to display an entirely different logo when scrolling, not just ...

Latest Typescript 1.8.4 compilation issue: "Compilation Error: Property 'result' is not found on the 'EventTarget' type."

I recently made the switch to using TypeScript in my Durandal application, upgrading from VS-2012 to VS-2015 and subsequently from TypeScript 0.9 to TypeScript 1.8.4. While transitioning, I encountered numerous build errors which I managed to resolve, exce ...

Creating a toggle link with 5 different states in coding

I have an HTML table where certain TDs contain inline styles, title tags, and links. I am looking to implement a feature where users can hide these elements by clicking the same icon multiple times. For example, on the first click, only styles are removed, ...

What is the best way to mandate the declaration or type of a function in TypeScript?

Let me present my dilemma: I am aiming to create a declaration file containing TypeScript function models. This file will be utilized by various individuals to build their own programs. To achieve this, I have crafted a def.d.ts file with a small example ...

tool for uploading and validating multiple file types

I have a file upload control for uploading multiple files. Here is an example: <ajaxToolkit:AsyncFileUpload ClientIDMode="Static" name="aa[]" BackColor="Azure" ForeColor="Black" OnClientUploadError="uploadError" OnClientUploadStarted="abc" ...

Utilize a function to send an AJAX email

In my JavaScript function, I have been attempting to send an email from a contact form. The validation checks are working correctly, but when the code reaches the point of sending the form, it gets stuck and doesn't receive any response from $.ajax. I ...

Display and verify the real value of JavaScript constructor

Currently, I am examining a Javascript datatable constructor function that involves handling checkbox elements. A variable named field is passed with all the values for the checkbox element, which are then broken down into separate variables for each elem ...

What is the best way to activate the filter in primeNG datatables angular 2 only when the enter key is pressed?

I'm utilizing PrimeNG datatables in Angular 2 and I want to know how to make the filter of PrimeNG datatable activate only when the user presses the enter key. Here is the base code: HTML: <div class="container-fluid single-col-full-width-contai ...