简体   繁体   中英

Datatables checkboxes start with some checkboxes checked

Can someone help me setup theCheckboxes extension for Datatables to start with some some checkboxes checked? The documentation on this matter can be found here , and although I've done everything that's required, it still fails to do what's supposed to do.

Basically I'm passing an array of the IDs that I want to be checked upon pageload, and I'm checking the ID of each row to check if it's contained in the array, but still all rows start unchecked.

jQuery(function($) {

  $('#questions-pool').DataTable({
    ordering: false,
    dom: '<"#upper-controls"lf>t<"#lower-controls"ip>',
    lengthMenu: [
      [10, 50, 100, -1],
      [10, 50, 100, 'All']
    ],
    initComplete: function(settings) {
      var api = this.api();
      var selected = [387, 386, 385, 384, 383, 382, 381, 380, 379, 378];
      alert(selected);

      api.cells(
        api.rows(function(idx, data, node) {
          alert(data[2]);
          return (selected.indexOf(data[2]) >= 0) ? true : false;
        }).indexes(),
        0
      ).checkboxes.select();
    },
    columnDefs: [{
      targets: 2,
      checkboxes: {
        selectAllPages: false,
      }
    }],
  });

});

You can find a working fiddle here . Everything is working fine, except for the desired rows selection at startup.

Any help will be greatly appreciated. I'm struggling with this for 2 days already...

So there were two issues (and bare with me since I don't even know jQuery nor any of the packages you were using).

The first is that the selected -list contain numbers while the data from the DOM your comparing to contain strings. Which means that they will never match.

The second thing was this piece:

    columnDefs: [{
      targets: 2,
      checkboxes: {
        selectAllPages: false,
      }
    }],

I changed it to

    'columnDefs': [
      {
        'targets': 0,
        'checkboxes': {
          'selectRow': true
        }
      }
    ],

because that's what the working example you passed used, and... I have no idea why but now it works, here's a working jsfiddle :)

https://jsfiddle.net/2y5hx1a4/12/

EDIT: Oh and a tip, it's way easier (imo) to debug using console.log("what you want to check") than alert :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM