Search code examples
jquerydatatablesyajra-datatable

How to get data-value from selected row datatables


I'm using jQuery Datatables with row selection using checkboxes and Select extension.

I need to get data value from the checkboxes rows. I used this code but I'm not able to get datas:

var rows_selected = table.column(0).checkboxes.selected();
$.each(rows_selected, function (index, rowId) {
    var data = table.row(index).data();
    fed_id = data['federation_id'];
    console.log(fed_id);
});

This is the html code of the table:

<table id="customerTable" class="table color-table info-table table-striped display dataTable no-footer dt-checkboxes-select" role="grid" aria-describedby="customerTable_info" style="width: 961px;">
<thead>
<tr role="row">
    <th class="dt-checkboxes-cell dt-checkboxes-select-all sorting_disabled" tabindex="0" aria-controls="customerTable" data-col="0" aria-label="">
        <input type="checkbox"></th>
    <th>Cognome</th>
    <th>Nome</th>
    <th>Codice Fiscale</th>
    <th>Federazione/Ente</th>
    <th>Codice tessera</th>
    <th>Data inizio</th>
    <th>Data fine</th>
    <th>Stato</th>
    <th></th>
</tr>
</thead>
<tbody>
<tr id="2554" data-federation_id="79" role="row" class="odd">
    <td class=" dt-checkboxes-cell"><input type="checkbox" class="dt-checkboxes"></td>
    <td class="sorting_1">Mario</td>
    <td>Rossi</td>
    <td>ddddddddd</td>
    <td>ddddddddd</td>
    <td></td>
    <td></td>
    <td></td>
    <td><span class="label label-info">DA INVIARE</span></td>
    <td>&nbsp;</td>
</tr>
<tr id="2558" data-federation_id="24" role="row" class="even">
    <td class=" dt-checkboxes-cell"><input type="checkbox" class="dt-checkboxes"></td>
    <td class="sorting_1">Mario</td>
    <td>Verdi</td>
    <td>ddddddddd</td>
    <td>ddddddddd</td>
    <td></td>
    <td></td>
    <td></td>
    <td><span class="label label-info">DA INVIARE</span></td>
    <td>&nbsp;</td>
</tr>

</tbody>
</table>

Solution

  • You can use the following jQuery to get the federation IDs for selected checkboxes:

    var checked_rows = $('input.dt-checkboxes:checkbox:checked').parents("tr");
    $.each(checked_rows, function (key, val) {
      console.log($(this).attr('data-federation_id'));
    });
    

    The first line gets all the selected checkboxes, and then finds the <tr> parents of those checkboxes.

    Then the code iterates over the found <tr> elements to extract each ID.

    Note that this jQuery does not use any DataTable functions, and is independent of the funtionality provided by DataTables. If you just want to grab the IDs, then this should be fine. If you want to change the content/behavior of your datatable, then this is probably not going to help.