0

Haven't yet seen an example of this anywhere. My multi-selection datatable loads from an array and uses a Gyrocode checkbox plugin to build a checkbox column. I'm fine with assigning user selections to an array - see button at top of table which outputs to console. However, I need to send one, or several, pre-selections to the datatable on initialisation so that the table starts up with those selections already highlighted and checked. Those selections can change, so I guess they'd need to be sent to the table as a variable of some sort. I'm stumped as to how to do this with my data structured as it is, although ideally I want to keep it as it is. Any ideas anyone? https://jsfiddle.net/sg0o3bwL/1/

<script src="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.js"></script>
<script src="https://gyrocode.github.io/jquery-datatables-checkboxes/1.2.10/js/dataTables.checkboxes.min.js"></script>
<link href="https://cdn.datatables.net/v/dt/dt-1.10.16/sl-1.2.5/datatables.min.css" rel="stylesheet" />

<button id="myselections" type="button" style="height: 20px; width: 150px;">See selections</button>

<form id="frm-example" action="/nosuchpage" method="POST">
  <table id="example" class="display select" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th></th>
        <!-- invisible col. for enable/disable separation -->
        <th>Order</th>
        <th>Sort</th>
        <th>Sort</th>
        <th>Sort</th>
        <th>Province</th>
        <th>City</th>
        <th>Status</th>
        <th>Sort</th>
        <th>Type</th>
      </tr>
    </thead>
  </table>
</form>




  $(function() {

  var MYdataSet1 = [
    ["", "1", "Bahrain", "Foulath", "Bahrain Steel BSCC", "Cobham", "Venice", "", "Sinter Plant, Coke plant, BF, BOF,Slab Caster, HSM, CRM ", ""],
    ["", "2", "Bombay", "Foulath", "United Stainless Steel Company", "Ealing", "Rome", "x", "Sinter Plant, Coke plant, BF, BOF,Slab Caster, HSM, CRM ", ""],
    ["", "3", "Bahrain", "Foulath (51%) :: Yamato Kogyo (49%)", "United Steel Company (Sulb)", "Kingston", "Milan", "", "Sinter Plant, Coke plant, BF, BOF,Slab Caster, HSM, CRM ", ""],
    ["", "4", "Universal Rolling", "", "", "acton", "Arson", "", "Sinter Plant, Coke plant, BF, BOF,Slab Caster, HSM, CRM ", ""],
    ["", "5", "Abul Khair Steel Products (AKSP)", "Jackson", "", "Barnes", "", "", "Sinter Plant, Coke plant, BF, BOF,Slab Caster, HSM, CRM", ""],
    ["", "6", "Bangladesh", "Anwar Isphat", "", "Sheen", "", "", "Sinter Plant, Coke plant, BF, BOF,Slab Caster, HSM, CRM ", ""],
    ["", "7", "Baizid Steel", "Baizid Steel", "", "Mayfair", "", "", "Sinter Plant, Coke plant, BF, BOF,Slab Caster, HSM, CRM ", ""],
    ["", "8", "Bengalh Steel Rolling Mills (BSRM)", "", "", "Park lane", "", "", "Sinter Plant, Coke plant, BF, BOF,Slab Caster, HSM, CRM ", ""],
  ];


// 'Initialise' DataTable

  var TradeDatatable = $('#example').DataTable({
    data: MYdataSet1,
    orderCellsTop: true,
    fixedHeader: true,
    scrollCollapse: true,
    paging: false,
    processing: true,
    orderCellsTop: true,

    'columnDefs': [{
        targets: 0,
        visible: false
      }, // This refers to the invisible column only - used to sort enabled from disabled rows

      {
        'targets': 1, // Refers to the Checkbox col. only
        'checkboxes': {
          'selectRow': true
        },
      },
      ],

    'select': {
      'style': 'multi'
    },

    "order": [
      [2, "asc"]
    ], // Default sorted column no.

    orderFixed: [0, 'desc'],
  });

//------------------

// List all ticked row selections

  $('#myselections').click(function(e) {

    var form = this;

    // Assume chkbxes to be in column 1 (col 0 is purposely blank)
    var rows_selected = TradeDatatable.column(1).checkboxes.selected();

    // Iterate over all selected checkboxes
    $.each(rows_selected, function(index, rowId) {

      // Create a hidden element
      $(form).append(
        $('<input>')
        .attr('type', 'hidden')
        .attr('name', 'id[]')
        .val(rowId)
      );
    });

    // Raw list of selected rows
    var RawRowNumbers = rows_selected.join(",");
    var CurrentSelectedArray = RawRowNumbers.split(','); // split string on comma

    function sortNumber(a, b) {
      return a - b;
    }
    CurrentSelectedArray.sort(sortNumber);
    console.log('Table selected_rows:', CurrentSelectedArray)

  });

});
3
  • What do you want selected? What will be the parameters? Commented Mar 3, 2019 at 20:43
  • 1
    Each row has a unique number (2nd entry in the array), so I suppose that needs to be the parameter. So I guess I'd tell the table to pre-select, say row 2, 3 and 6, or whatever. Commented Mar 3, 2019 at 21:03
  • Added a bit to my answer to show some more info. Commented Mar 3, 2019 at 21:21

2 Answers 2

3

There are a couple of things you can do here, but either way, you need to add

select: true, to your table settings...like so:

data: MYdataSet1,
orderCellsTop: true,
fixedHeader: true,
scrollCollapse: true,
paging: false,
processing: true,
orderCellsTop: true,
select: true,

Then after the table is loaded, you can run something like this:

TradeDatatable.rows([1,2]).select();

This will select rows 2 and 3 (row 1 actually is 0). However, it selects BEFORE the sorting you have applied. If you take out your sorting, you'll see the rows selected exactly in the order in the array above. There are lots of ways besides the row number that you can use to select what you need. See here: https://datatables.net/reference/api/rows().select()

You can select by a class on the row (which you can add) or the content of a specific column of the row, but without knowing what parameters you want your search based on, it's hard to say.

UPDATE:

You can also select based on the content in a column:

TradeDatatable.rows( function ( idx, data, node ) {
    return data[2] === 'Bahrain';
} )
.select();

This would select any row where the 3rd column (2nd in index) has the word "Bahrain"

Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant! Can't believe I didn't work this out for myself - thought it was far more complex. Very clear explanation and much appreciated.
Glad it helped.
0

This is using the DataTables Select plugin.

               "rowCallback": function (row, data, index) {
                if (data['IsDuplicate'] == "1") {
                    $('td', row).css('background-color', 'Yellow');
                } else { 
                    this.api().row(row).select();                                  
                    $(row).removeClass('selected');
                }
            },
               

This should be pretty easy to adapt, but my data had some duplicates in it, so I wanted everything checked (pre-selected), except for the duplicate row.

It is looking for data.IsDuplicate == 1, and if it is true, it highlights the row yellow. If it is false, it uses the Select API to select the row.

What you would need to do is look for the data that you want to use to preselect the row, and use that instead of IsDuplicate. Then use the appropriate part of the if statement to accomplish what you want to do.

If you want the row to be highlighted as selected, remove the line: $(row).removeClass('selected');

So far, this code is doing exactly what I needed it to do.

I'm going to include this code. It will find a checkbox in in the first column and check it if the conditions are met. However, since it doesn't use the Select API, the checked rows won't show up as selected. This would still be useful if you need to manually check a checkbox in your table. You will have to change a few things if this checkbox input isn't in the first column:

               "rowCallback": function (row, data, index) {
                if (data['IsDuplicate'] == "1") {
                   $('td', row).css('background-color', 'Yellow');
                } else {
                   let element = $(row).children()[0]; // find('td:eq(0):first-child');
                   let chkBox = element.firstChild;
                   chkBox.setAttribute("checked", true);
                }
            },
            select: {
                style: 'os',
                selector: 'td:first-child'
            },

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.