DaveH
DaveH

Reputation: 7335

jQuery Datatables - how to check if row with given id is on the current page

I need to check to see if a row with an known ID is present on the page that datatables is currently displaying

I'm using the following code

let target = table.row('#'+ ns.currentClientId, {page:'current'});

When I look at target.data() it always seems to contain the row identified by the "id" column, regardless of whether it is on the currently displayed page or not.

Am I misunderstanding / misusing the API?

Here's a fiddle that isolates the problem

The data in the table is populated via an API call, and the id is set using the rowId property when the DataTable is created.

let table = $(selector).DataTable({
                    "ajax": {
                        "url": "/api/client/v1/client",
                        "type": "GET",
                        "dataSrc": "items",
                        "beforeSend": function (request) {
                            Object.keys(headers).forEach(function (key) {
                                request.setRequestHeader(key, headers[key]);
                            });
                        }
                    },
                    "order": [],
                    retrieve: true,
                    "select": true,
                    select: {
                        style: 'single'
                    },
                    stateSave: true,
                    info: false,
                    lengthChange: false,
                    ordering: false,
                    rowId: "id",
                    "columns": [
                        {"data": "name"},
                        {"data": "dateofbirth"},
                        {
                            "data": "id",
                            "visible": false
                        }
                    ]
                });

When rendered, the HTML looks like this ( snippet )

enter image description here

Upvotes: 1

Views: 1272

Answers (1)

annoyingmouse
annoyingmouse

Reputation: 5699

I managed to break JSFiddle trying to solve this! How very odd! Anyway, I think this should do what you need:

$(document).ready(function () {
  var table = $('#example').DataTable({
    "drawCallback": function (settings) {
      $('#tiger').hide();
      var api = this.api();
      api.rows({ page: 'current' }).every(function (rowIdx, tableLoop, rowLoop) {
        var rowNode = this.node();
        if ($(rowNode).attr('id') === 'id_1') {
          $('#tiger').show();
        }
      });
    }
  });
});

I'm using the built-in drawCallback function to iterate over the rows and get the raw HTML used to generate the DataTable.

Working example (hint: I've changed your CSS to remove the flash): https://jsfiddle.net/annoyingmouse/6ex5bkzq/

Upvotes: 1

Related Questions